In [1]: class A(object):
...: def __init__(self):
...: self.a = 'a'
...:
In [2]: class B(A):
...: def __init__(self):
...: self.b = 'b'
...:
In [3]: temp = B()
In [4]: print(temp.a)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-a47164864387> in <module>()
----> 1 print(temp.a)
因为B没有属性a所以会报错,这个问题可以通过super解决
In [5]: class B(A):
....: def __init_(self):
....: self.b = 'b'
....: super(A, self).__init__()
....:
In [6]: temp = B()
In [7]: print(temp.a)
a
我想问的就是下面这中情况,super的调用在self = 'b'之后
,为什么print(temp.a)的值会是b而不是a
?如果是C++中的构造函数好像会将B类中a的值覆盖,各位网友能否解释一下。
In [8]: class B(A):
....: def __init__(self):
....: self.a = 'b'
....: super(A, self).__init__()
....:
In [9]: temp = B()
In [10]: print(temp.a)
b
输出a
应该是super用错了
其实可以写成这样: