python - 从类访问私有(private)模块变量

标签 python oop python-2.7 private

我正在尝试理解 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 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 - 从类访问私有(private)模块变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21236818/

相关文章:

python - 如何并排绘制具有不同 X 坐标的条形图

php - 如何创建库

python - 通过 python ctypes 调用带有 char* 参数的 C 函数 python2 和 python3 的区别

python - 用新值替换文件中的值数组

python - 用于训练的 Keras 特征形状

python - 同一应用程序中的几个(两个)Flask 对象

python - 创建一个类,用于存储字典并在 Python 3 中根据字典值更改设置对象属性

python - 使用 Python Selenium webdriver 登录雅虎电子邮件帐户

java - 创建方法时 Eclipse 表现得很奇怪

ios - 无法覆盖 Swift 中的变量