My Blog
Articles related to programming, computer science, technology and research.

19/04/2018 Categories: Python Programming. No Comments on Inheritance and Polymorphism in Python

Contents1 Inheritance2 Polymorphism2.1 Method Overriding Inheritance   Creating a new class from existing class is known as inheritance. The class from which features are inherited is known as base class and the class into which features are derived into is called derived class.   Inheritance promotes reusability of code by reusing already existing classes. Inheritance […]

Inheritance

 

Creating a new class from existing class is known as inheritance. The class from which features are inherited is known as base class and the class into which features are derived into is called derived class.

 

Inheritance promotes reusability of code by reusing already existing classes. Inheritance is used to implement is-a relationship between classes.

 

Following hierarchy is an example representing inheritance between classes:

 

vehicle-hierarchy

 

Syntax for creating a derived class is as follows:

 

 

Following example demonstrates inheritance in Python:

 

 

Polymorphism

 

Polymorphism means having different forms. Based on the context, a variable, function, or an object can have different meaning. As inheritance is related to classes, polymorphism is related to methods. In Python, method overriding is one way of implementing polymorphism.

 

Method Overriding

 

In method overriding, a base class and the derived class will have a method with the same signature. The derived class method can provide different functionality when compared to the base class method.

 

When a derived class method is created and the method is invoked, the derived class method executes overriding the base class method. Following example demonstrates method overriding:

 

 

Related Links:

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up