例如:
class Foo:
def __init__(self):
self.bar = "baz"
def test(self):
return "secret value that can only accessed in this function!!"
我该怎么做:
x = Foo()
with x.test() as f:
print(f)
# "secret value that can only be accessed in this function!!"
没有引发错误吗?
答案 0 :(得分:2)
您可以使用contextlib.contextmanager
:
import contextlib
class Foo:
@contextlib.contextmanager
def bar(self):
yield 'secret'
并像这样使用它:
>>> x = Foo()
>>> with x.bar() as f:
... print(f)
secret
但是请注意,这不足以“隐藏”外部操作中的变量(因此您的秘密永远不会是真正的秘密)。 Python是动态的,因此大多数“安全措施”都依赖于一个不成文的约定,即用户不要尝试并积极地规避它们。
答案 1 :(得分:1)
您应该需要使用contextmanager的理由,但是仅作为示例,您可以执行以下操作:
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`")
用法将返回:
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`"
更多信息,位于:
https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager