嘗試使用我的小方法,但出現以下錯誤:
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__()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句