如何使python类成为上下文管理器

问题描述 投票:-1回答:2

我相信我必须在代码中犯一个简单的错误。我这样定义我的课程

class Simple():
    def __init__(self):
        self.string = "Hello World"

    def __enter__(self):
        pass

    def __exit__(self):
        pass

并这样称呼它:

with Simple() as simple_test:
    print(simple_test.string)

我收到以下错误:

    print(simple_test.string)
AttributeError: 'NoneType' object has no attribute 'string'

为什么是我的班级None

python contextmanager
2个回答
1
投票

__enter__方法必须返回self

def __enter__(self):
    return self

0
投票

[__enter__应该返回您想在as子句中绑定的任何内容,请参阅python docs

class Simple():
    def __init__(self):
        self.string = "Hello World"

    def __enter__(self):
        return self

    def __exit__(self):
        pass
© www.soinside.com 2019 - 2024. All rights reserved.