看看这个。请注意,该类B会覆盖A的a()方法。In [1]: class A(object): ...: def __init__(self): ...: self.a() ...: def a(self): ...: print "A.a()" ...: ...: In [2]: class B(A): ...: def __init__(self): ...: super(B, self).__init__() ...: def a(self): ...: print "B.a()" ...: ...: In [3]: b = B()B.a()没有惊喜。现在,看看这个。请注意,现在被覆盖的方法是__a()。In [7]: class A(object): ...: def __init__(self): ...: self.__a() ...: def __a(self): ...: print "A.__a()" ...: ...: In [8]: class B(A): ...: def __init__(self): ...: super(B, self).__init__() ...: def __a(self): ...: print "B.__a()" ...: ...: In [9]: b = B()A.__a()这种行为使我感到惊讶。谁能解释为什么A.__a()被称为而不是B.__a()?什么__special__约__a?更新:阅读了肖恩的答案后,我想看看是否可以覆盖名称混乱的方法并得到以下结果:In [11]: class B(A): ....: def __init__(self): ....: super(B, self).__init__() ....: def _A__a(self): ....: print "B._A__a()" ....: ....: In [12]: b = B()B._A__a()
添加回答
举报
0/150
提交
取消