进入上下文管理器,使用实例的方法。

huangapple go评论95阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年8月8日 20:27:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76859558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定