python – 使用上下文管理器时,对象变为None
作者:互联网
为什么这不起作用:
class X:
var1 = 1
def __enter__(self): pass
def __exit__(self, type, value, traceback): pass
with X() as z:
print z.var1
我明白了:
print z.var1
AttributeError: 'NoneType' object has no attribute 'var1'
解决方法:
将X的定义更改为
class X(object):
var1 = 1
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass
with将__enter __()方法的返回值指定为之后的名称.您的__enter __()返回None,它已分配给z.
我还将类更改为新类(这对于使其工作并不重要).
标签:with-statement,python 来源: https://codeday.me/bug/20190927/1824350.html