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} |
我已经读了一些关于双下划线如何导致属性名被"损坏"的内容,但是在上面的两种情况下,我都希望相同的名称被损坏。
对象名称前的单下划线和双下划线的含义是什么?
你知道这是怎么回事吗?
名称管理发生在评估
(实际上,这可能并不完全正确。在评估
从文档中
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.
号
在定义类之后,您正在分配您的属性