Python上下文管理器



试图使用我的小方法,但我得到了以下错误:

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()

相关内容

最新更新