Is there a way to use super () to call the __init__ method of each base class in Python?

Suppose I have Python code:

class Mother: def __init__(self): print("Mother") class Father: def __init__(self): print("Father") class Daughter(Mother, Father): def __init__(self): print("Daughter") super().__init__() d = Daughter() 

This script prints "Daughter." Is there a way to ensure that all methods of __init__ class classes are called? One of the methods that I came up with was the following:

 class Daughter(Mother, Father): def __init__(self): print("Daughter") for base in type(self).__bases__: base.__init__(self) 

This script prints "Daughter", "Mother", "Father". Is there a good way to do this using the super () method or another method?

+5
source share
1 answer

Raymond Hettinger explained this very well in his presentation of Super Super Supered of from PyCon 2015. Short answer: yes, if you design like that, and call super().__init__() in each class

 class Mother: def __init__(self): super().__init__() print("Mother") class Father: def __init__(self): super().__init__() print("Father") class Daughter(Mother, Father): def __init__(self): super().__init__() print("Daughter") 

The name super unfortunate; it really works through the base classes.

+5
source

All Articles