Python Inheritance and Polymorphism

In this tutorial we want to talk about Python Inheritance and Polymorphism, so we know that Python is an object oriented programming language, and it supports the concepts of inheritance and polymorphism. these concepts allows you to create classes that are more flexible, reusable and maintainable. in this article we want to discuss what is inheritance and polymorphism and how they can be used in Python classes.

 

 

 

Inheritance in Python Classes

Inheritance is a process in which a new class is created by inheriting the properties and methods of an existing class. existing class is called the parent class or base class, and the new class is called child class or derived class. in Python inheritance is done by using  super() function and __init__() method.

 

 

 

This is an example of Python Inheritance

In the above example Animal is the parent class, Dog and Cat are child classes. __init__() method is used to initialize the name attribute, which is common to all animals.  speak() method is abstract in the Animal class, and is implemented in the Dog and Cat classes. this allows us to create different types of animals that can speak in different ways.

 

 

This will be the result

Python Inheritance and Polymorphism
Python Inheritance and Polymorphism

 

 

 

 

Polymorphism in Python Classes

Polymorphism is the ability of an object to take on multiple forms. in Python polymorphism is done by using of inheritance and method overriding. Method overriding is the process of redefining a method in child class that was already defined in the parent class. this allows child class to change the behavior of the method without changing its name or parameters.

 

 

 

This is polymorphism example in Python

In the above example Shape is an abstract class that defines abstract method area. Rectangle and Circle classes are derived from Shape and implement their own versions of the area method. shapes list contains objects of both classes. when we call shape.area() in the loop, and correct version of the area method is called depending on the type of the object.

 

 

 

 

This will be the result

Python Polymorphism
Python Polymorphism

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×