&引用;加上;Python中的语句
我在代码中实现了很多类。现在我意识到,对于为所有这些类调用的每个方法,我需要添加一行:&引用;加上;Python中的语句,python,proxy,Python,Proxy,我在代码中实现了很多类。现在我意识到,对于为所有这些类调用的每个方法,我需要添加一行: with service as object: 所以我尝试使用代理模式来自动完成这项工作,这是我的示例代码 class A(object): def __init__(self, name): self.name = name def hello(self): print 'hello %s!' % (self.name) def __ente
with service as object:
所以我尝试使用代理模式来自动完成这项工作,这是我的示例代码
class A(object):
def __init__(self, name):
self.name = name
def hello(self):
print 'hello %s!' % (self.name)
def __enter__(self):
print 'Enter the function'
def __exit__(self, exc_type, exc_value, traceback):
print 'Exit the function'
#
class Proxy(object):
def __init__(self, object_a):
# object.__setattr__(self, '_object_a', object_a)
self._object_a = object_a
def __getattribute__(self, name):
service = object.__getattribute__(self, '_object_a')
# with service as service:
result = getattr(service, name)
return result
if __name__=='__main__':
a1 = A('A1')
b = Proxy(a1)
b.hello()
a2 = A('A2')
b = Proxy(a2)
b.hello()
一切正常,我有输出:
hello A1!
hello A2!
但是当我用语句取消注释时,我有一个错误
Enter the function
Exit the function
Traceback (most recent call last):
File "/home/hnng/workspace/web/src/test.py", line 30, in <module>
b.hello()
File "/home/hnng/workspace/web/src/test.py", line 24, in __getattribute__
result = getattr(service, name)
AttributeError: 'NoneType' object has no attribute 'hello'
输入函数
退出函数
回溯(最近一次呼叫最后一次):
文件“/home/hnng/workspace/web/src/test.py”,第30行,在
b、 你好()
文件“/home/hnng/workspace/web/src/test.py”,第24行,在__
结果=getattr(服务,名称)
AttributeError:“非类型”对象没有属性“hello”
您的\uuuu enter\uu
方法将返回None
,而不是返回对象。应改为:
def __enter__(self):
print 'Enter the function'
return self
您的\uuuu enter\uuu
方法将返回None
,而不是返回对象。应改为:
def __enter__(self):
print 'Enter the function'
return self
谢谢,这正是我需要做的!谢谢,这正是我需要做的!