Python double underscore mangling

前端 未结 2 1871
死守一世寂寞
死守一世寂寞 2021-01-18 04:41

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}

c         


        
2条回答
  •  情歌与酒
    2021-01-18 05:26

    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.)

提交回复
热议问题