Zet*_*tor 4 python with-statement
{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()}
Run Code Online (Sandbox Code Playgroud)
执行此py文件,控制台显示以下消息:
Enter
Exit
instant.method()
AttributeError: 'NoneType' object has no attribute 'method'
Run Code Online (Sandbox Code Playgroud)
无法找到方法?
__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()
Run Code Online (Sandbox Code Playgroud)
产量
Enter
Method
Exit
Run Code Online (Sandbox Code Playgroud)
如果__enter__没有返回self,则None默认返回.因此,instant赋值None.这就是您收到错误消息的原因
' NoneType '对象没有属性'method'
(我的重点)