使用“with”语句访问Python类方法

2024-03-29 02:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

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: intestselfonlysecretthatfooinit
2条回答

您应该需要一个使用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

What is the python "with" statement designed for?

您可以使用^{}

import contextlib

class Foo:
   @contextlib.contextmanager
   def bar(self):
       yield 'secret'

像这样使用:

>>> x = Foo()

>>> with x.bar() as f:
...     print(f)
secret

但是请注意,这不足以“隐藏”变量以防外部操作(因此您的秘密永远不会是真正的秘密)。Python的核心是动态的,因此大多数“安全措施”都依赖于一个不成文的约定,即用户不会尝试并主动规避它们。你知道吗

相关问题 更多 >