Open Source Projects
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
# some attributes of the parent class
# some methods of the parent class
# some attributes of the child class
# some methods of the child class
Note! The attributes and methods of the ParentClass is inherited by the ChildClass.
In the following Python program we have a parent class Employee and a child class Manager.
# parent class
def __init__(self, id, name):
print("Hello from Employee.__init__()")
self.id = id
self.name = name
print("ID: %s" %self.id)
print("Name: %s" %self.name)
# child class
def __init__(self, id, name, project):
print("Hello from Manager.__init__()")
self.project = project
print("Project: %s" %self.project)
# object of Manager class
obj = Manager(1, 'Jane Doe', 'Android App')
The above code will print the following output.
Hello from Employee.__init__()
Hello from Manager.__init__()
Name: Jane Doe
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 id and name of the employee which we are saving using the self keyword.
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 id, name and project of the employee.
Using the super method in the child class we call the __init__ method of the parent class.
Inside the __init__ method of the Manager class we are calling the __init__ method of the Employee class and passing the id and name value.
We are assigning the value of project to the instance attribute project using the self keyword.
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 Employee class.
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 employeeDetail and projectDetail methods which prints the values set for the employee.
Have fun learning :-)
Copyright © 2014 - 2019 DYclassroom. All rights reserved.
rendered in 0.0233 sec