这是因为 Python 中的“隐藏”变量的存储方式不同。那里有一点点魔法。
这是一个为什么它不起作用的例子:
class Base(object):
__flag = 'base'
_other_flag = 'base'
def __init__(self) :
pass
@classmethod
def flag(self):
return self.__flag
@classmethod
def other_flag(self):
return self._other_flag
class Derived(Base):
__flag = 'derived'
_other_flag = 'derived'
print 'base flag', Base.flag()
print 'derived flag', Derived.flag()
print 'base other flag', Base.other_flag()
print 'derived other flag', Derived.other_flag()
# Note the following 2 statements:
print 'base flag property', Derived._Base__flag
print 'derived flag property', Derived._Derived__flag
print 'base other flag property', Base._other_flag
print 'derived other flag property', Derived._other_flag
正如您在底部看到的那样,它存储在不同的变量中,并在Base.flag
方法中默默地转换为该变量。