擅长:python、mysql、java
<p>您应该需要一个使用ContextManager的理由,但仅作为一个示例,您可以这样做:</p>
<pre><code>from contextlib import contextmanager
class Foo:
def __init__(self):
self.bar = "baz"
@contextmanager
def test(self):
print("doing something before entering `with block`")
yield "secret value that can only accessed in this function!!"
print("doing something else after exiting `with block`")
</code></pre>
<p>用法将返回:</p>
<pre><code>x = Foo()
with x.test() as f:
print(f)
# "doing something before entering `with block`"
# "secret value that can only be accessed in this function!!"
# "doing something else after exiting `with block`"
</code></pre>
<p>更多信息请访问:</p>
<p><a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="nofollow noreferrer">https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager</a></p>
<p><a href="https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for">What is the python "with" statement designed for?</a></p>