Polymorphism

Polymorphism - poly means many and morphs means forms. Polymorphism is the ability of an object to have more than one forms. For example, we have two or more objects from the same base class with methods with same name but their implementation is different.

In Python, polymorphism is achieved through two methods,

  1. Method Overriding
  2. Duck Typing

Method Overriding

Method overriding is a form of polymorphism where a subclass provides a specific implementation for a method that is already defined in its superclass. When an object of the subclass is used, the overridden method in the subclass is called instead of the method in the superclass.

In this example, both Dog and Cat classes inherit from the Animal class and override the speak method. When the animal_sound function is called with different objects, it demonstrates polymorphism by calling the appropriate overridden speak method.

Duck Typing

Python follows the principle of duck typing, which means that the type or class of an object is determined by its behavior (methods and attributes) rather than by its explicit type. If an object behaves like a certain class, it is treated as an instance of that class, regardless of its actual class.

In this example, both Duck and Human classes have a sound method. The make_sound function takes an argument and calls the sound method on it. This demonstrates polymorphism through duck typing, where the function works with objects of different classes as long as they have a compatible interface (in this case, a sound method).

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min