我正在尝试理解python范围规则.为此,我尝试从同一模块中的类访问“非常私有”变量
bar = "bar"
_bar = "underscore"
__bar = "double underscore"
def foo():
print bar
print _bar
print globals()["__bar"]
print __bar
class Foo:
def __init__(self):
print bar
print _bar
print globals()["__bar"]
print __bar #NameError: global name '_Foo__bar' is not defined
foo()
Foo()
它因NameError而失败.我在规范中找不到任何相关内容.那么,为什么它失败了,这种行为描述的地方呢?
解决方法:
在类定义中,所有以双下划线开头的名称都会被破坏;重写以包含类名作为前缀.
这是一个支持在类中将名称标记为“私有”并保护它不被子类覆盖的功能.见identifiers documentation:
Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.
最好不要在模块全局变量上使用双下划线前缀;没有必要这样做,单个下划线足以表明该值是模块内部的.
如果您遇到这样的值,请创建一个未损坏的别名,或使用globals()[name].
标签:python,python-2-7,oop,private
来源: https://codeday.me/bug/20191007/1864524.html