2014-10-29 66 views
4

我試圖運行此代碼:隨着語句設置變量無

class A: 
    def __enter__(self): 
     print "enter" 
    def __exit__(self, *args): 
     print "exit" 
    def __init__(self, i): 
     self.i = i 
with A(10) as a: 
    print a.i 

而且我得到這個錯誤:

enter 
exit 
Traceback (most recent call last): 
File ".last_tmp.py", line 9, in <module> 
print a.i 
AttributeError: 'NoneType' object has no attribute 'i' 

什麼是錯我的語法?

回答

10

您將需要從__enter__返回self

def __enter__(self): 
    print "enter" 
    return self 

with聲明實際上相當於:

a = A(10).__enter__() # with A(10) as a: 
try: 
    print a.i # Your with body 
except: 
    a.__exit__(exception and type) 
    raise 
else: 
    a.__exit__(None, None, None) 

所以,你需要返回的東西,否則a會有的價值None(默認返回值),並且None沒有名爲i的屬性,因此您將獲得AttributeError

2

對象的__enter__方法的返回值是分配給as關鍵字後面的名稱的值。你的方法(隱含地)返回None,導致你看到的錯誤。相反,__enter__應該返回self,以便將由A(10)創建的對象分配給a