例如:
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!!"
不犯错误?你知道吗
Tags:
您应该需要一个使用ContextManager的理由,但仅作为一个示例,您可以这样做:
用法将返回:
更多信息请访问:
https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager
What is the python "with" statement designed for?
您可以使用^{} :
像这样使用:
但是请注意,这不足以“隐藏”变量以防外部操作(因此您的秘密永远不会是真正的秘密)。Python的核心是动态的,因此大多数“安全措施”都依赖于一个不成文的约定,即用户不会尝试并主动规避它们。你知道吗
相关问题 更多 >
编程相关推荐