Nearby lessons

90 of 108

Python - Inheritance

Detailed Tutorial Notes

Method overriding:

What ever members available in the parent class are bydefault available to the child class through
inheritance. If the child class not satisfied with parent class implementation then child class is
allowed to redefine that method in the child class based on its requirement. This concept is called

overriding.

Overriding concept applicable for both methods and constructors.

Demo Program for Method overriding:

1) class P:
2) def property(self):
3) print('Gold+Land+Cash+Power')
4) def marry(self):
5) print('Appalamma')
6) class C(P):
7) def marry(self):
8) print('Katrina Kaif')

9)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
From Overriding method of child class,we can call parent class method also by using super()

Gold+Land+Cash+Power

Katrina Kaif

method.

1) class P:
2) def property(self):
3) print('Gold+Land+Cash+Power')
4) def marry(self):
5) print('Appalamma')
6) class C(P):
7) def marry(self):
8) super().marry()
9) print('Katrina Kaif')

10)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
class P:
def __init__(self):
print('Parent Constructor')

Gold+Land+Cash+Power

Appalamma

Katrina Kaif

Demo Program for Constructor overriding:

4)

5) class C(P):
6) def __init__(self):
7) print('Child Constructor')

8)

🐍
main.py
Python 3 Runtime
Loading Editor...
Output Preview
In the above example,if child class does not contain constructor then parent class constructor will

be executed

From child class constuctor we can call parent class constructor by using super() method.
Demo Program to call Parent class constructor by using super():
1) class Person:
2) def __init__(self,name,age):
3) self.name=name
4) self.age=age

5)

6) class Employee(Person):
7) def __init__(self,name,age,eno,esal):
8) super().__init__(name,age)
9) self.eno=eno
10) self.esal=esal

11)

12) def display(self):
13) print('Employee Name:',self.name)
14) print('Employee Age:',self.age)
15) print('Employee Number:',self.eno)
16) print('Employee Salary:',self.esal)

17)

18) e1=Employee('Durga',48,872425,26000)
19) e1.display()
20) e2=Employee('Sunny',39,872426,36000)
21) e2.display()

Output:

Employee Name: Durga

Employee Age: 48

Employee Number: 872425

Employee Salary: 26000

Employee Name: Sunny

Employee Age: 39

Employee Number: 872426

Employee Salary: 36000

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Python - Polymorphism