This question already has answers here:
What is the meaning of a single and a double underscore before an object name?
(15个答案)
3年前关闭。
当我使用
让我举一个例子:
口译员提出了一个错误:
因此,我们可以看到它试图将
我以为名称更改只能用于类变量(当我使用
是我不知道的明确定义的行为,还是某种Python错误?
我在CPython 3.5上测试过
(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,重点是我的)