Python Inheritance

There’s an important aspect of Object-Oriented Programming, that enables code reusability instead of writing similar code over again. In reality, picture this. Your father has a spare truck that’s still functional, and you are in need of a truck to transport some farm produce from your farmland to the home. Although you’re buoyant enough to purchase a new truck, wisdom is to collect (inherit) your dad’s spare truck. That’s all about Python Inheritance. The ability to create a new class from an existing one.

At the end of this article, you’ll have complete knowledge of the following:

  • What is python Inheritance?
  • Use of python
  • Inheritance syntax explanation?
  • Types of Python Inheritance
  • Multiple inheritances overriding

In conclusion, you’ll be all equipped and fit for some inheritance adventure.

What is Python Inheritance?

In simple terms, Python Inheritance is the collection of class properties from an existing one. As the name implies in real life, you simply inherit the properties of the parent class from the child class. Also known as the base class and derived class respectively. The parent class is the class being inherited from while the child class is the class that inherits from the parent’s class.

The concept of inheritance is valued because of its Importance which is not limited to:

  • When class A inherits from class A, then all the subclasses in B will have the same quality as A
  • Its cut out work repetition,ntou don’t have to repeat a code over again, you just inherit from the parent class

In order to be able to move further, we must see the inheritance Syntax and understand it’s components before moving unto the type of Python Inheritance.

Python Inheritance syntax explained

The python derived inheritance can be gotten by the syntax: class BaseClass:

  Body of base class

class DerivedClass(BaseClass):

  Body of derived class. For a clear understanding, see an example below

Example 1: to demonstrate inheritance

Python Input

# A Python program to demonstrate inheritance
# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
class Person(object):
    # Constructor
    def __init__(self, name):
        self.name = name
    # To get name
    def getName(self):
        return self.name
    # To check if this person is an employee
    def isEmployee(self):
        return False
# Inherited or Subclass (Note Person in bracket)
class Employee(Person):
    # Here we return true
    def isEmployee(self):
        return True
# Driver code
emp = Person("Simon1")  # An Object of Person
print(emp.getName(), emp.isEmployee())
emp = Employee("Monday 2") # An Object of Employee
print(emp.getName(), emp.isEmployee())

Output:


Simon1 False
Monday2 True

We shall return to do some practice, at the meantime, let’s get done with some theory

Types of Python Inheritance

There are five types of Python Inheritance, and they’re explained below:

Single Inheritance

This is when a derived class is sourced from one parent class.

Example:

Python Input

#syntax_of_single_inheritance
class Brands:               #parent_class
    brand_name_1 = "Amazon"
    brand_name_2 = "Ebay"
    brand_name_3 = "OLX"
class Products(Brands):       #child_class
    prod_1 = "Online Ecommerce Store"
    prod_2 = "Online Store"
    prod_3 = "Online Buy Sell Store"
obj_1 = Products()          #Object_creation
print(obj_1.brand_name_1+" is an "+obj_1.prod_1)
print(obj_1.brand_name_2+" is an "+obj_1.prod_2)
print(obj_1.brand_name_3+" is an "+obj_1.prod_3)

Output:

Amazon is an Online Ecommerce Store
Ebay is an Online Store
OLX is an Online Buy Sell Store

Multiple inheritances

when a child’s class inherits from more than one parent class. Example:

Python Input

class Calculation1: 
    def Summation(self,a,b): 
        return a+b; 
class Calculation2: 
    def Multiplication(self,a,b): 
        return a*b; 
class Derived(Calculation1,Calculation2): 
    def Divide(self,a,b): 
        return a/b; 
d = Derived() 
print(d.Summation(1,70))
print(d.Multiplication(10,20))
print(d.Divide(4,2))

Output:

71
200
2.0

Multilevel inheritance

Multilevel inheritance is one child class inheriting from one parent class and one grandchild, class inheriting from the child class.

Example:

Python Input

class Animal: 
    def speak(self): 
        print("Animal Speaking") 
#The child class Dog inherits the base class Animal 
class Dog(Animal): 
    def bark(self): 
        print("dog barking") 
#The child class Dogchild inherits another child class Dog 
class DogChild(Dog): 
    def eat(self): 
        print("Eating bread...") 
d = DogChild() 
d.bark() 
d.speak() 
d.eat()

Output:


dog barking
Animal Speaking
Eating bread...

Hierarchical inheritance

This is creating more than one child class from one parent class.

Example:

Python Input

#example
class Brands:                      #parent_class
    brand_name_1 = "Amazon"
    brand_name_2 = "Ebay"
    brand_name_3 = "OLX"
class Products(Brands):            #child_class
    prod_1 = "Online Ecommerce Store"
    prod_2 = "Online Store"
    prod_3 = "Online Buy Sell Store"
class Popularity(Brands):        #grand_child_class
    prod_1_popularity = 100
    prod_2_popularity = 70
    prod_3_popularity = 60
class Value(Brands):
    prod_1_value = "Excellent Value"
    prod_2_value = "Better Value"
    prod_3_value = "Good Value"
obj_1 = Products()          #Object_creation
obj_2 = Popularity()
obj_3 = Value()
print(obj_1.brand_name_1+" is an "+obj_1.prod_1)
print(obj_1.brand_name_1+" is an "+obj_1.prod_1)
print(obj_1.brand_name_1+" is an "+obj_1.prod_1)

Output:


Amazon is an Online Ecommerce Store
Amazon is an Online Ecommerce Store
Amazon is an Online Ecommerce Store

Hybrid inheritance

This type of inheritance is the combination of all the above inheritances. The Hybrid inheritance is efficient when you want to perform the inheritance operations without limitations.

Example:

Python Input

# Python program to demonstrate
# hybrid inheritance
class School:
     def func1(self):
         print("This function is in school.")
class Student1(School):
     def func2(self):
         print("This function is in student 1. ")
class Student2(School):
     def func3(self):
         print("This function is in student 2.")
class Student3(Student1, School):
     def func4(self):
         print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()

Output:


This function is in school.

Method Overriding

Method overriding is simply the ability to change the performance of the child class that is already in the parent class. However, to override inheritance, these three steps must be satisfied which are:

  • Inheritance must be present when you want to override. As you can not override without deriving a child class from a parent class.
  • There should be the same number of parameters in the child and parent’s class.

An example of the above statement note this example is overriding a multiple overriding :

Python Input

# Python program to demonstrate
# overriding in multiple inheritance
# Defining parent class 1
class Parent1():
    # Parent's show method
    def show(self):
        print("Inside Parent1")
# Defining Parent class 2
class Parent2():
    # Parent's show method
    def display(self):
        print("Inside Parent2")
# Defining child class
class Child(Parent1, Parent2):
    # Child's show method
    def show(self):
        print("Inside Child")
# Driver's code
obj = Child()
obj.show()
obj.display()

Output:


Inside Child
Inside Parent2

Summary

Remember that…

In simple terms, Python Inheritance is the collection of class properties from an existing one.

The concept of inheritance is valued because of its Importance which is not limited to:

  • When class A inherits from class A, then all the subclasses in B will have the same quality as A
  • Its cut out work repetition, you don’t have to repeat a code over again, you just inherit it from the parent class

There are five types of Python Inheritance, which are:

  • Single Inheritance
  • Multiple inheritances
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Method overriding is simply is the ability to change the performance of the child class that is already in the parent class

At the end of this article, you’ve learned:

  • What is python Inheritance?
  • Use of python
  • Inheritance syntax explanation?
  • Types of Python Inheritance
  • Multiple inheritances overriding

It’s required of you to put in all the efforts required for success. For a helping hand, see the Python Tutorial. Good Luck coding!

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment