{class foo(object):
def __enter__ (self):
print("Enter")
def __exit__(self,type,value,traceback):
print("Exit")
def method(self):
print("Method")
with foo() as instant:
instant.method()}
执行这个 py 文件,控制台显示以下消息:
Enter
Exit
instant.method()
AttributeError: 'NoneType' object has no attribute 'method'
找不到方法?
__enter__
应该返回self
:
class foo(object):
def __enter__ (self):
print("Enter")
return self
def __exit__(self,type,value,traceback):
print("Exit")
def method(self):
print("Method")
with foo() as instant:
instant.method()
yields
Enter
Method
Exit
If __enter__
不返回self
,然后返回None
默认情况下。因此,instant
被赋值None
。这就是您收到错误消息的原因
'NoneType' 对象没有属性 'method'
(我的重点)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)