What is super() in python

Oct. 6, 2020, 8:36 a.m.

In python programming language, super() method return an object which allows you to refer to the super class, let us see how this works using the example below

class Person: def __init__(self, name, age): self.name = name self.age = age



class Employee(Person): def __init__(self, name, age, salary): super().__init__(name, age) # this will call the person __init__ self.salary = salary



emp = Employee('Baraka', 28, 120000)


print('The employee name is: ', emp.name)

print('The employee age is: ', emp.age)

print('The employee salary is: ', emp.salary)

The output of the above code is

The employee name is:  Baraka
The employee age is:  28
The employee salary is:  120000 

In the above example, we have two classes, the first class is Person class and the second is an Employee class

The person class has an __init__ method which takes in name and age such that when you create a Person object , the name and age get set automatically by the __init__ method .

When creating a Person object you have to pass in name and age , for example , p1 = Person("Baraka", 28)

The second class is the Employee class which inherits from the Person class, and therefore it gets all the properties and methods of the parent class.

In our example, the Employee class takes in name , age and salary , this can be seen in its __init__ method

After the __init__ method of the Employee class , we have this line super().__init__(name, age) , this means that we are calling the __init__ method of the parent class, in our example , the parent class is the Person class.

Now we have this line self.salary = salary , here we are adding the salary property in the __init__ method of the Person class to the value of salary which was provided in the Employee class __init__ method.

Resources

photo by Oskar Yildiz on unsplash

Keep Learning