我正在尝试理解 python 作用域规则。为此,我尝试从同一模块中的类访问“非常私有(private)”变量
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
。我在规范中找不到任何相关内容。那么,为什么它会失败以及这种行为在哪里描述?
最佳答案
在类定义中,所有以双下划线开头的名称都会被破坏;重写以包含类名作为前缀。
此功能支持在类中将名称标记为“私有(private)”,并防止其被子类覆盖。请参阅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 namedHam
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 - 从类访问私有(private)模块变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21236818/