在类方法中引用私有模块全局变量

时间:2014-09-11 15:34:19

标签: python

我最近偶然发现了Python的一个奇怪的行为,它与模块变量及其在类中的使用有关。同一模块的方法,我找不到任何信息,所以我转向StackOverflow:)

这是一个可以直接运行的小python脚本,它显示了我的问题:

__foo = "private foo"
foo = "public foo"

class Test:

    def test(self):
        self.test_public()
        self.test_private()

    def test_private(self):
        global __foo
        print("{0}".format(__foo))

    def test_public(self):
        global foo
        print("{0}".format(foo))

test = Test()
test.test()

奇怪的是,这个简单的测试将在test_private调用失败。此脚本的输出如下:

public foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 21, in <module>
    test.test()
  File "test.py", line 9, in test
    self.test_private()
  File "test.py", line 13, in test_private
    print("{0}".format(__foo))
NameError: global name '_Test__foo' is not defined

正如您所看到的,这适用于foo变量,但__foo的名称会因类的名称而受到损坏,从而导致崩溃。

我在Python文档中找不到这种行为,我想知道这是否有意,或者我是否做错了什么?

在任何情况下,有没有办法解决这个限制?在我的用例中,我用公共变量替换了我的私有变量,但我真的想再次私有变量...

提前感谢您的帮助。

编辑:我知道Python中没有reall私有方法/变量,这是一个演讲的数字。双下划线是我工作时使用的惯例,所以我需要尽可能地坚持下去。

0 个答案:

没有答案
相关问题