gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:51:44 25 4
gpt4 key购买 nike

我正在尝试理解 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com