[英]Python context manager
尝试使用我的小方法,但出现以下错误:
class mycls:
def __init__(self):
...
def __enter__(self):
...
def little(self):
...
def __exit__(self, exc_type, exc_val, exc_tb):
...
with mycls() as cl:
cl.little()
with cl:
cl.little()
with cl:
cl.little()
cl.little()
错误:
AttributeError: 'NoneType' object has no attribute 'little'
with
语句不会将mycls
本身的实例绑定到cl
,而是将该实例的__enter__
方法的返回值绑定。 目前, mycls.__enter__
返回None
,因此观察到错误。 __enter__
更改为
def __enter__(self):
return self
并且您的代码应该按预期工作。
像这样的代码
with foo as bar:
...
是(忽略很多细节)大致相同
x = foo()
bar = x.__enter__()
...
x.__exit__()
您需要从__enter__
返回self
:
class mycls:
def __enter__(self):
return self
def __exit__(self, *_):
pass
def little(self):
pass
with mycls() as cl:
cl.little()
with cl:
cl.little()
with cl:
cl.little()
cl.little()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.