I was experimenting with class inheritance using the code below:
>>> class Class1:
clsattr1 = 1
def __init__(self):
self.selfattr1 = 1
>>> class Class2:
clsattr2 = 2
def __init__(self):
self.selfattr2 = 2
>>> class ClassA(Class1, Class2):
def __init__(self):
super(Class1, self).__init__()
super(Class2, self).__init__()
>>> classa = ClassA()
>>> classa.clsattr1, classa.clsattr2
(1, 2)
>>> classa.selfattr1
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
classa.selfattr1
AttributeError: 'ClassA' object has no attribute 'selfattr1'
>>> classa.selfattr2
2
>>> classa.__dict__
{'selfattr2': 2}
As you can tell, the child class (ClassA
) did not inherit the instance attributes of Class1
, the first parent class (the selfattr1
attribute). What is the explanation for this behavior? Also, should I change my code so that ClassA
inherits the instance attributes of both Class1
and Class2
(preferably using super()
, or something similar)?