【发布时间】:2012-11-09 23:49:38
【问题描述】:
我对这种行为有点困惑(使用 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}
我已经阅读了一些关于双下划线如何导致属性名称“错位”的内容,但我预计在上述两种情况下都会出现相同的名称错位。
What is the meaning of a single- and a double-underscore before an object name?
有什么想法吗?
【问题讨论】:
-
修改的目的正是为了防止您的第二种情况正常工作。目的是对外部代码隐藏属性。
标签: python attributes python-3.x private-methods double-underscore