使用__处理全局变量的Python名称 [英] Python name mangling on global variable with __
问题描述
当我使用 __
创建模块级变量并尝试在类的方法(使用 global
关键字)中访问它时,发生了名称更改.
When I created a module-level variable with __
and tried to access it inside a method of a class (using global
keyword) the name-mangling occured.
让我展示一个例子:
__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()
口译员提出了一个错误:
Interpreter raised an error:
NameError:未定义名称'_TestClass__test'
因此我们可以看到它试图将 __ test
命名为 _TestClass__test
.
So as we can see it tried to name-mangle __test
into _TestClass__test
.
我认为名称处理只能用于类变量(当我使用 self
或类名访问它们时).
I thought that name-mangling should be used only for class variables (when I access them with self
or class name).
这是我不知道的明确定义的行为,还是某种Python错误?
Is it a well-defined behaviour that I have not be aware of or it is some kind of Python bug?
我在CPython 3.5上进行了测试
I tested it on CPython 3.5
推荐答案
任何标识符,格式为
__ spam
(至少两个前划线,在文本上最多替换一个结尾的下划线)_classname__spam
,其中classname
是当前的类名,其中前导下划线被去除.这种处理不加考虑到标识符的句法位置,只要它出现在类的定义之内.
Any identifier of the form
__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, whereclassname
is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
(来自 Python文档,重点是我的
这篇关于使用__处理全局变量的Python名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!