[英]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.