名称加扰用于确保子类不会意外覆盖其超类的私有方法和属性。它并非旨在防止从外部故意访问。
例如:
>>> class Foo(object):... def __init__(self):... self.__baz = 42... def foo(self):... print self.__baz... >>> class Bar(Foo):... def __init__(self):... super(Bar, self).__init__()... self.__baz = 21... def bar(self):... print self.__baz...>>> x = Bar()>>> x.foo()42>>> x.bar()21>>> print x.__dict__{'_Bar__baz': 21, '_Foo__baz': 42}当然,如果两个不同的类具有相同的名称,它就会崩溃。



