Polymorphism In Python Example

Polymorphism Definition

Polymorphism built with two words "poly" and "morphs". Poly means many and Morphs means form, shape.

Polymorphism enables using a single interface with input of different datatypes, different class or may be for different number of inputs.

Polymorphism is exhibiting differing behavior in differing conditions. Polymorphism can be used in two way.

  • Method Overloading and
  • Method Overriding

Method Overloading in Python

Python does not support method overloading like other languages. It will just replace the last defined function as the latest definition. We can however try to achieve a result similar to overloading using *args or using an optional arguments.

These methods can perform a similar or different function.

Example:



Output:

 10
 42


Example 1: Method Overriding

Polymorphism means the ability to take various forms. In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class.



Output:

 function() method from class B
 function() method from class A

Example 2: Method Overriding



Output:

 function() method from class A
 function() method from class B