Let's suppose I have a bit of 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 anyway to ensure that all of the __init__ methods of the bases classes are called? One method I came up with to do this was:
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 nice way to do this using super() or another method?
__init__() of the superclass ( Square ) will be called automatically. super() returns a delegate object to a parent class, so you call the method you want directly on it: super(). area() . Not only does this save us from having to rewrite the area calculations, but it also allows us to change the internal .
Understanding Python super() with __init__() methods When this method is called it allows the class to initialize the attributes of the class. In an inherited subclass, a parent class can be referred with the use of the super() function.
Using Super(): Python super() function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'.
The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.
Raymond Hettinger explained this really well in his talk Super Considered Super from PyCon 2015. The short answer is yes, if you design this way, 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
is unfortunate, it really works its way through the base classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With