In this tutorial we will learn about inheritance in Python.
Inheritance is one of the core concepts of OOP - Object Oriented Programming. It helps us to create hierarchy.
Inheritance is a concept were a child class inherits the properties and methods from the parent class.
The class that is used to create other classes is called the parent class or super class.
The class that inherits the attributes and methods of the parent class is called the sub class or child class.
Following is the syntax of inheritance in Python.
# parent class class ParentClass: # # some attributes of the parent class # # # some methods of the parent class # class ChildClass(ParentClass): # # some attributes of the child class # # # some methods of the child class #
Note! The attributes and methods of the
ParentClass is inherited by the
In the following Python program we have a parent class Employee and a child class Manager.
# parent class class Employee: def __init__(self, id, name): print("Hello from Employee.__init__()") self.id = id self.name = name def employeeDetail(self): print("ID: %s" %self.id) print("Name: %s" %self.name) # child class class Manager(Employee): def __init__(self, id, name, project): super().__init__(id, name) print("Hello from Manager.__init__()") self.project = project def projectDetail(self): print("Project: %s" %self.project) # object of Manager class obj = Manager(1, 'Jane Doe', 'Android App') # output print("-----Manager Detail-----") obj.employeeDetail() print("-----Project Detail-----") obj.projectDetail()
The above code will print the following output.
Hello from Employee.__init__() Hello from Manager.__init__() -----Manager Detail----- ID: 1 Name: Jane Doe -----Project Detail----- Project: Android App
We have the parent class
Employee and the child class
Manager which inherits attributes and methods of the parent class.
In this class we have the
__init__ method that takes two arguments
name of the employee which we are saving using the
Then we have the
employeeDetail method that prints the detail of the employee.
This class also includes the
__init__ method and it takes three arguments
project of the employee.
super method in the child class we call the
__init__ method of the parent class.
__init__ method of the Manager class we are calling the
__init__ method of the Employee class and passing the
We are assigning the value of
project to the instance attribute
project using the
Then, there is the
projectDetail method that prints out the project name.
We create an object of the
Manager class which inherits all the properties and methods of the
While instantiating an object of the Manager class we are passing the id, name and project name of the employee.
Finally, we are calling the
projectDetail methods which prints the values set for the employee.