Another essential use of the function super() is to call the initializer of the parent class from inside the initializer of the child class.
Note: It is not necessary that the call to super() in a method or an initializer is made in the first line of the method.
Below is an example of using super() in an initializer inside the child class.
xxxxxxxxxx
class ParentClass():
def __init__(self, a, b):
self.a = a
self.b = b
class ChildClass(ParentClass):
def __init__(self, a, b, c):
super().__init__(a, b)
self.c = c
obj = ChildClass(1, 2, 3)
print(obj.a)
print(obj.b)
print(obj.c)
Initializers are called when an object of a class is created. See the example below:
xxxxxxxxxx
class Employee:
# defining the properties and assigning them None
def __init__(self, ID, salary, department):
self.ID = ID
self.salary = salary
self.department = department
# creating an object of the Employee class with default parameters
Steve = Employee(3789, 2500, "Human Resources")
# Printing properties of Steve
print("ID :", Steve.ID)
print("Salary :", Steve.salary)
print("Department :", Steve.department)