Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用“with”语句访问Python类方法_Python_Python 3.x - Fatal编程技术网

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

使用“with”语句访问Python类方法,python,python-3.x,Python,Python 3.x,例如: Foo类: 定义初始自我: self.bar=baz def testself: 返回只能在此函数中访问的机密值!! 我如何做到这一点: x=Foo x.test作为f: printf 只能在此函数中访问的机密值!! 在不引发错误的情况下?您可以使用: 导入上下文库 Foo类: @contextlib.contextmanager def barself: 交出“秘密” 并像这样使用它: >>>x=Foo >>>以x.bar作为f: ... printf 秘密 但是请注意,这不足

例如:

Foo类: 定义初始自我: self.bar=baz def testself: 返回只能在此函数中访问的机密值!! 我如何做到这一点:

x=Foo x.test作为f: printf 只能在此函数中访问的机密值!! 在不引发错误的情况下?

您可以使用:

导入上下文库 Foo类: @contextlib.contextmanager def barself: 交出“秘密” 并像这样使用它:

>>>x=Foo >>>以x.bar作为f: ... printf 秘密 但是请注意,这不足以隐藏一个变量以防外部操作,因此您的秘密永远不会是真正的秘密。Python的核心是动态的,因此大多数安全措施都依赖于一种不成文的约定,即用户不会尝试并主动规避这些约定。

您可以使用:

导入上下文库 Foo类: @contextlib.contextmanager def barself: 交出“秘密” 并像这样使用它:

>>>x=Foo >>>以x.bar作为f: ... printf 秘密
但是请注意,这不足以隐藏一个变量以防外部操作,因此您的秘密永远不会是真正的秘密。Python的核心是动态的,因此大多数安全措施都依赖于一种不成文的约定,即用户不会尝试并主动绕过它们。

使用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`"
更多信息,请访问:


您应该需要使用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`"
更多信息,请访问:


with用于ContextManager,并不是所有的方法都会返回一个上下文管理器,看看这是一个。你想实现什么?如果Foo.test不使用实例,为什么它是一个实例方法?如果Foo真的什么都不做,为什么不让test成为一个普通函数呢?为什么需要使用with语句而不仅仅调用方法?我同意@Selcuk。这是关于主题的另一个很好的资源:。with用于ContextManager,并非所有方法都将返回上下文管理器,请看这是一个。你想实现什么?如果Foo.test不使用实例,为什么它是一个实例方法?如果Foo真的什么都不做,为什么不让test成为一个普通函数呢?为什么需要使用with语句而不仅仅调用方法?我同意@Selcuk。这是关于该主题的另一个很好的资源:。