I've been trying to understand how to make sure all super().__init__()
s run when writing a class that inherits from two unrelated classes. Based on answers such as this and others like it, calling super(DerivedClass, self).__init__()
should do the trick ("newer style").
So I've set up a dummy example:
class One():
def __init__(self):
print("One runs")
self.one = 1
class Two():
def __init__(self):
print("Two runs")
self.two = 2
class Three(One, Two):
def __init__(self):
super(Three, self).__init__()
print("Three runs")
three = Three()
print(three.two)
To my biggest surprise, this results in an error when running on Python 3.9.7. The exact output I get is:
One runs
Three runs
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/var/folders/xd/f8xs148x2j18h636phmf27zh0000gq/T/ipykernel_7384/3344160392.py in <module>
16
17 three = Three()
---> 18 print(three.two)
AttributeError: 'Three' object has no attribute 'two'
This makes me super confused. Is this not the right way to do it with the "newer style"? What am I missing?
super(...).__init__
– one for each base. See the first case "1. The base classes are unrelated, standalone classes." Other answers are showing a similar pattern for this case.super(DerivedClass, self).__init__()
should do the trick" is not the case and what to do instead. If you can edit this question to clarify in how far the information in the other one is not sufficient, it will go to the reopen process.