如何使python类成为上下文管理器
我这样定义我的类:如何使python类成为上下文管理器,python,contextmanager,Python,Contextmanager,我这样定义我的类: 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) 这样称呼它: class Si
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)
这样称呼它:
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
?方法必须返回self
:
def __enter__(self):
return self
\uuuu enter\uuuu
应在as
子句中返回要绑定的内容,请参阅
因为您的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
我想你想要这个:
class Simple():
def __init__(self):
self.string = "Hello World"
def __enter__(self):
return self
def __exit__(self):
pass
simple\u test
被分配了\uuuuuuuuuuuuuuuuuuuuuuuuu
方法的返回值-你需要从\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>方法返回
。我今天花了几个小时在这个问题上,没有规范?\uuuu退出\uuuu
方法只应执行清理。它不会返回任何东西…我(最终意识到)的理解是它应该是\uuuuuuu退出(self,exc\u type,exc\u value,exc\u traceback)
?是的,如果你想在\uuuu退出
中使用它,你可以。如果您只想传递
它,并且添加了\uuuuuuuuuuuuuuuuuuuuuuuuuuuuu
它只是为了实现上下文管理器,那么您可以将\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
函数不带参数(仅限self),顺便说一句,如果它对您有帮助,请接受答案,以便帮助其他正在处理类似问题。