我正在尝试运行这段代码:
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'
我的语法有什么问题?
最佳答案
您需要从 __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
。
关于python - With 语句将变量设置为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637482/