This question already has answers here:
What is the meaning of a single and a double underscore before an object name?
                                
                                    (15个答案)
                                
                        
                                3年前关闭。
            
                    
当我使用__创建模块级变量并尝试在类的方法(使用global关键字)中访问它时,发生了名称更改。

让我举一个例子:

__test = 'asd'  # module level variable with __


class TestClass(object):
    def test(self):
        global __test
        print(__test)  # trying to access this variable


a = TestClass()
a.test()


口译员提出了一个错误:

NameError: name '_TestClass__test' is not defined

因此,我们可以看到它试图将__test命名为_TestClass__test

我以为名称更改只能用于类变量(当我使用self或类名访问它们时)。

是我不知道的明确定义的行为,还是某种Python错误?

我在CPython 3.5上测试过

最佳答案

任何形式为__spam的标识符(至少两个下划线,
  在文本上最多替换一个下划线)
  _classname__spam,其中classname是当前类名,其中前导下划线被去除。这种处理是无视的
  只要标识符出现在标识符的句法位置上
  在类的定义内。


(摘自the Python documentation,重点是我的)

09-04 14:38
查看更多