In multiple inheritance, I want to use instance variables of parent class.
For example, class C inherits from class A and class B, and reads these parent classes variable.
class D is similar as class C but different in not using super().
class A(object):
def __init__(self):
self.a = 1
class B(object):
def __init__(self):
self.b = 2
class C(A,B):
def __init__(self):
super().__init__()
print(self.a)
print(self.b)
class D(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self)
print(self.a)
print(self.b)
I expect class C has instance variable a and b
However, it doesn't have b?
In [58]: c = C()
1
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-58-1ef1f2c22529> in <module>
----> 1 c = C()
<ipython-input-56-414cdffff47f> in __init__(self)
3 super().__init__()
4 print(self.a)
----> 5 print(self.b)
6
AttributeError: 'C' object has no attribute 'b'
On the other hand, class D has both a and b.
In [59]: d = D()
1
2
Looking at method resolution order, class C and class D is same.
In [60]: C.mro()
Out[60]: [__main__.C, __main__.A, __main__.B, object]
In [61]: D.mro()
Out[61]: [__main__.D, __main__.A, __main__.B, object]
Why class C fails?