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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章