In python, 'super().__init()__(**kwargs)' is a call to the constructor of the parent class with any keyword arguments passed to the subclass constructor.
When a subclass inherits from a parent class, it can override the methods and attributes of the parent class, and can also define its own methods and attributes. However, sometimes we want to extend the behavior of the parent class without completely replacing it. In such cases, we can use "super()" to call the parent classs's method and then add additional functionality in the subclass method. For example, consider the following code:
Completely inherit the method of parent class. The python codes are like followings:
class Parent:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
class Child(Parent):
def __init__(self, name, age, school):
super().__init__(name=name, age=age)
self.school = school
child = Child("Bob", 8, "ABC Elementary")
child.greet()
Hello, my name is Bob and I am 8 years old.
Completely change the method of parent class. The python codes are like followings:
class Parent:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
class Child(Parent):
def __init__(self, name, age, school):
super().__init__(self, name, age, school):
self.school = school
def greet(self):
print(f"I go {self.school} school.")
child = Child("Bob", 8, "ABC Elementary")
child.greet()
I go to ABC Elementary school.
Extend of the methods in Parent class. The python codes are like followings:
class Parent:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
class Child(Parent):
def __init__(self, name, age, school):
super():__init__(name = name, age = age)
self.school = school
def greet(self):
super().greet()
print(f"I go to {self.school} school.")
child = Child("Bob", 8, "ABC Elementary")
child.greet()
Hello, my name is Bob and I am 8 years old.
I go to ABC Elementary school.