Python double underscore mangling

五迷三道 提交于 2020-01-30 04:50:51

问题


I am a bit confused by this behavior (using python 3.2):

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}

I've read up a bit on how double-underscores cause attribute names to be "mangled", but I would have expected the same name-mangling in both cases above.

What is the meaning of a single- and a double-underscore before an object name?

Any ideas what's going on here?


回答1:


Name mangling occurs during the evaluation of a class statement. In the case of Bar, the __cache attribute is not defined as part of the class, but rather added to a specific object after the fact.

(Actually, that may not be entirely correct. Name mangling may occur during the evaluation of the __new__ method; I do not know. But regardless, your __cache is added explicitly to a single object, not added by the class code.)




回答2:


From the docs

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.

You are assigning your property after the class has been defined



来源:https://stackoverflow.com/questions/13498151/python-double-underscore-mangling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!