gnr*_*gnr 6 python attributes double-underscore private-methods python-3.x
我对这种行为感到有点困惑(使用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}
我已经阅读了一些关于双下划线如何导致属性名称被"损坏"的内容,但在上述两种情况下我都希望使用相同的名称.
有什么想法在这里发生了什么?
che*_*ner 10
在评估class语句期间发生名称重整.在这种情况下Bar,__cache属性未定义为类的一部分,而是在事后添加到特定对象.
(实际上,这可能不完全正确.在__new__方法的评估过程中可能会出现名称错误;我不知道.但无论如何,您将__cache被明确地添加到单个对象中,而不是由类代码添加.)
| 归档时间: | 
 | 
| 查看次数: | 3167 次 | 
| 最近记录: |