关于属性:Python双下划线修改

Python double underscore mangling

我对这种行为有点困惑(使用python 3.2):

1
2
3
4
5
6
7
8
9
10
11
12
13
class Bar:
    pass

bar = Bar()
bar.__cache = None
print(vars(bar))        # {'__cache': None}

class Foo:
    def __init__(self):
        self.__cache = None

foo = Foo()
print(vars(foo))        # {'_Foo__cache': None}

我已经读了一些关于双下划线如何导致属性名被"损坏"的内容,但是在上面的两种情况下,我都希望相同的名称被损坏。

对象名称前的单下划线和双下划线的含义是什么?

你知道这是怎么回事吗?


名称管理发生在评估class语句期间。在Bar的情况下,__cache属性不定义为类的一部分,而是在事实之后添加到特定对象中。

(实际上,这可能并不完全正确。在评估__new__方法时,可能会出现名称混乱,我不知道。但是无论如何,您的__cache是显式地添加到单个对象中的,而不是由类代码添加的。)


从文档中

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 in front of the name, with leading underscores removed, and
a single underscore inserted in front of the class 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.

在定义类之后,您正在分配您的属性