英文:
Entering to context manager with method of instance
问题
我想在我的类中实现一个上下文管理器,它不会创建一个新的实例,而是通过某个方法在现有实例上调用。
这样,在使用时,它会像下面这样:
some_instance = SomeClass()
with some_instance.context_manager_method():
... # 做一些事情
这种方式可行吗?
英文:
I would like to implement a context manager in my class that wouldn't create a new instance but would be invoked on an existing one using a certain method,
so that in usage, it would look as follows:
some_instance = SomeClass()
with some_instance.context_manager_method():
... # do something
is it possible?
答案1
得分: 1
当然。您可以使用contextlib.contextmanager
来创建任何您想要的上下文管理器。以下是一个代码片段:
from contextlib import contextmanager
class SomeClass:
@contextmanager
def context_manager_method(self):
# 设置
yield
# 清理
英文:
Sure. You can use contextlib.contextmanager
to create any context manager that you want. Here's a snippet:
from contextlib import contextmanager
class SomeClass:
@contextmanager
def context_manager_method(self):
# setup
yield
# teardown
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论