What is super() in python
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
In the above example, we have two classes, the first class is Person class and the second is an Employee class
The employee name is: Baraka The employee age is: 28 The employee salary is: 120000
The person class has an
__init__ method which takes in
age such that when you create a Person object , the
age get set automatically by the
__init__ method .
When creating a Person object you have to pass in
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
salary , this can be seen in its
__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
photo by Oskar Yildiz on unsplash
- How to send SMS using Django
- django messages framework example
- What is os.path.dirname() method in python