2013-03-07 83 views
0

我在我的代碼中實現了很多類。現在我認識到了調用所有這些類的每一個方法,我需要添加一行:」with「在Python中的語句

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! 

但是,當我取消了with聲明,我有錯誤

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' 

回答

6

__enter__方法返回None而不是返回的對象。它應該是:

def __enter__(self): 
    print 'Enter the function' 
    return self 
+0

謝謝,這正是我需要做的! – nam 2013-03-07 11:06:54