Take a look at this.
Note that class B
overrides A
's a()
method.
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()
No surprises there.
Now, take a look at this.
Note that the method now being overridden is __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()
This behaviour surprised me.
Can anyone explain why A.__a()
is called instead of B.__a()
?
Anything __special__
about __a
?
Update:
After reading Sean's answer I wanted to see if I could override the name mangled method and got this result:
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()
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…