Python OOP – Inheritance and its Types in Python
|In this Python article, we will discuss inheritance along with its implementation, types, use in class, and methods with some examples. Let’s get started.
1. What is Inheritance and its Uses in Python?
Inheritance can be defined as a way that allows one class to inherit certain characteristics and operations from any other class.
The parent class is that class which permits other class to inherit its attributes and methods.
The child class is the class that inherits the methods and attributes from the parent class.
Read More about Python Classes and Objects or OOPS in Python
There are several benefits of inheritance:
- It helps in representing relationships of real world (eg family tree).
- The code can be reused and saves time from writing the same code again.
- It allows user to add common features without making any modification/duplication in child classes.
- It is transitive in nature, if one class Y was inherited from a class X then all subclass of Y will get automatic inherited properties from class X.
Syntax: class Parent: <<body of parent>> class Child(Parent): <= Name of Parent class <<body of child class>>
Let’s implement the minimal example where Manager
class extends its behavior from Employee
class. Since Manager
does not have any additional behavior we can skip the implementation for the Manager
class.
class Employee: def __init__(self, dept, salary): self.department = dept self.income = salary def displaydetails(self): print("Department and income of employee are: ", self.department, " ", self.income) class Manager(Employee): pass emp = Employee(1024, 7500000) emp.displaydetails() manager = Manager(1031, 8600000) manager.displaydetails()
Output Department and income of employee are: 1024 7500000 Department and income of employee are: 1031 8600000
2. How to use __init__() function in Inheritance?
As in the above example, we used the pass keyword but we can also use the __init__()
function in the child class rather than only using it in the parent class. This method is also known as subclassing.
Note: The __init__()
function will be automatically called each time when we create a new object.
Once we create the __init__()
function inside the child class, the __init__()
function of parent class will not be inherited by the child class.
Hence, it can be simply said that __init__()
function of a child class overrides the __init__()
function of the inherited parent class.
class Machine: # parent class def __init__(self): print("This is the parent class: Machine") def feature1(self): print("Machine has feature1") class SimpleMachine(Machine): # child class def __init__(self): # call super() function Machine.__init__(self) print("This is the child class: Simplemachine") def feature2(self): print("SimpleMachine has feature2") m1 = SimpleMachine() m1.feature1() m1.feature2()
Output This is the parent class: Machine This is the child class: Simplemachine Machine has feature1 SimpleMachine has feature2
In the above program, the child class SimpleMachine
inherits certain characteristics and methods from the parent class Machine
. We may add several other features and develop certain changes according to the requirement.
3. What is the use of Super Method in Inheritance?
In Python, we can use the function super()
which enables the child class to access an attribute, invoke functions, and methods of the parent class.
Adding methods means adding some more functions to a child class. For example, we can add display_name
function. This function will be accessible only via Staff
class but child class can access all inheritable members of the Employee
class.
class Employee: def __init__(self, dept, salary): self.department = dept self.income = salary def display_details(self): print("Department and income of employee are: ", self.department," ", self.income) class Staff(Employee): def __init__(self, dept, salary, nameofemp): super().__init__(dept, salary) self.name = nameofemp def display_name(self): print("Welcome", self.name, ", your department is:", self.department, " and your salary is", self.income) print("Employee") emp = Employee(1024, 7500000) emp.display_details() print("\nStaff") stf = Staff(1031, 8600000, "Jordan") stf.display_details() stf.display_name()
Output Employee Department and income of employee are: 1024 7500000 Staff Department and income of employee are: 1031 8600000 Welcome Jordan , your department is: 1031 and your salary is 8600000
4. Different types of inheritance in Python
4.1. Single Inheritance
Simple to implement and understand, when a child class inherits properties and methods from a single parent class only. All the above program examples are based on single inheritance.
4.2. Multiple Inheritance
Multiple inheritance happens when a child class inherits properties and methods from multiple parents or base classes.
We pass all the parent classes in the bracket of the child class, separated by commas.
Syntax: class Parent1: body of parent class Parent2: body of parent class Parent3: body of parent class Child(Parent1, Parent2, Parent3): body of child class
4.3. Multilevel inheritance
In this, there are multiple levels of inheritance. For a top-level class A, there exists a class B that extends A, and then another class C that extends class B.
It can be understood as a staircase, in a multi-level way, and forming a child and grandchild relationship.
Syntax: class Parent1: body of parent class child1(Parent1): body of child class class child2(child1): body of child class
4.4. Hierarchical Inheritance
In this inheritance, a hierarchical structure is formed. It is like a tree structure. For a top-level class A, there can be multiple classes B, C, D that extends class A. Multiple derived classes are created from a single base.
Syntax: class Parent1: body of parent class child1(Parent1): body of child class class child2(Parent1): body of child class class child3(Parent1): body of child class
4.5. Hybrid Inheritance
This inheritance includes the use of a combination of hierarchical and multiple inheritances.
It is a combination of more than one inheritance type.
Syntax: class Parent1: body of parent class child1(Parent1): body of child class class child2(Parent1): body of child class class GrandChild(child1): body of grand child class
5. What is Method Overriding in Python?
We extend the functionality of a method from the parent class by overriding that method in the child class. It enables us to provide custom behavior for the child instances without changing the class contract.
Suppose one class B is derived from class A and both the class have __init__() method.
In such conditions, the method in the base class(A) is overridden by the method of the child class(B). Hence, whenever we have an instance of class B then the __init__()
of class B gets preference over the __init__
of class A,
Generally, when we override methods of a base class, we try to extend the definition instead of direct replacing it. The same is being done by calling the method in the base class from the one in the derived class. Using the built-in function super()
is a better idea in such cases.
Two built-in functions isinstance()
and issubclass()
can be used to keep an eye on inheritances and check the relations.
The function isinstance()
returns True
if the object is an instance of the class or other classes derived from it.
The function issubclass()
returns True
if the class is inherited from another class.
Syntax:>>> isinstance(objectname,classname)
True/False(output)
True/
>>> issubclass(class1,class2)
(output)
False
class A(): def __init__(self): self.val1 = 2 class B(A): def __init__(self): A.__init__(self) refA = A() refB = B() print(f"Is refA instance of A - {isinstance(refA, A)}") print(f"Is refA instance of B - {isinstance(refA, B)}") print(f"Is refB instance of A - {isinstance(refB, A)}") print(f"Is refB instance of B - {isinstance(refB, B)}") print(f"Is A subclass of B - {issubclass(A, B)}") print(f"Is B subclass of A - {issubclass(B, A)}")
Output Is refA instance of A - True Is refA instance of B - False Is refB instance of A - True Is refB instance of B - True Is A subclass of B - False Is B subclass of A - True
6. How to Prevent Inheritance of Private Members of Parent Class?
Inheritance allows child class to inherit every possible thing but there may some instances where we do not want child class to inherit from parent class and hence we create some instance variables as private.
We can prevent an instance variable to be inherited by adding double underscores before its name.
Let’s see an example for preventing a variable from inheritance.
class A(): def __init__(self): self.val1 = 2 # d is private instance variable self.__val2 = 8 class B(A): def __init__(self): self.val3 = 4 A.__init__(self) ref = B() print(ref.val2) # Error
Output Traceback (most recent call last): File "main.py", line 14, in print(ref.val2) AttributeError: 'B' object has no attribute 'val2'
In the above output, we can see the error which indicates the prevention of inheritance for the particular variable.
7. Conclusion
Finally, if we sum up, in this article we learned about different properties of inheritance along with their implementation, we have covered:
- What is Inheritance in python and how can we use it?
- What is the role of using
__init__()
function in Inheritance? - What is the use of super function and methods in inheritance?
- Various types of inheritance (Single, multiple, multilevel, hybrid, hierarchical).
- What is method overriding in Python?
- How can we prevent the inheritance of private members of the parent class from any child class?
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?