Python Polymorphism

Polymorphism is one of the fundamental concepts in object-oriented programming (OOP). The word comes from Greek, meaning “many forms,” and it allows objects of different types to respond to the same method or operation in their own way.

In practice, it shows up in operators, built-in functions, and class methods that behave differently depending on the data type or object.

Here, Polymorphism = “Many Forms”

That means, same function, operator, or method name → different behavior depending on the object it’s applied to.

The following are the types of Polymorphism in Python:

  1. Operator Polymorphism
  2. Function Polymorphism
  3. Run-Time Polymorphism (Method Overriding)

Operator Polymorphism

The + operator works differently depending on the data type. Here, the operator is the same, but the behaviour is different:

Integers

Let us use the + operator to add three numbers:

# Sum of three integers
a = 5
b = 10
c = 20

print("Sum = ",a + b + c)  

Output

35

Strings

Let us see another example to use the + operator with Strings to concatenate:

# Concatenation with the string type 
str1 = "Steve"
str2 = "Smith"
print(str1 + " " + str2)  

Output

Steve Smith

Function Polymorphism

Some functions can easily run with multiple data types. It follows the fundamentals of one function, many forms.

For example, the built-in len() function can work with many data types. Let us see some examples:

Strings

The len() returns the number of characters if the type is string:

print(len("What a beautiful day."))

Output

21

Tuples

The len() returns the number of elements in a tuple:

print(len(("Cricket", "Football", "Volleyball", "Hockey", "Archery")))

Output

5

Dictionary

The len() returns the key-value pairs in a Dictionary:

person = {
    "name": "Jack",
    "age": 25,
    "city": "Sweden"
}

print(len(person))

Output

3

Run-Time Polymorphism (Overriding)

Run-time polymorphism in Python refers to the ability of methods to behave differently based on the object that is invoking them, achieved primarily through method overriding. It allows subclasses to provide specific implementations of methods defined in their parent class, and the decision of which method to execute happens at run-time.

In Python, runtime polymorphism (dynamic) is supported through method overriding, while compile-time polymorphism (static, e.g., method overloading) is not natively supported.

Let us see the differences first:

Compile Time vs Run Time Polymorphism in Python

Example

The code below explains the concept of Run-Time Polymorphism in Python:

# Animal is the parent class.
# It defines a generic speak() method.
class Animal:
    def speak(self):
        print("Animal makes a sound")

# Four Derived Classes (Method Overriding)
# Each subclass (Dog, Cat, Bear, Cow) inherits from Animal.
# They override the speak() method with their own implementation.
# This is the essence of run-time polymorphism: the same method name (speak) behaves differently depending on the object type.

class Dog(Animal):
    def speak(self):
        print("Dog barks")

class Cat(Animal):
    def speak(self):
        print("Cat meows")
        
class Bear(Animal):
    def speak(self):
        print("Bears roar")
        
class Cow(Animal):
    def speak(self):
        print("Cows moo")
        
# A list of objects is created: one of each subclass plus the base class.
# Even though they all share the same interface (speak()), their behavior differs.

animals = [Dog(), Cat(), Bear(), Cow(), Animal()]

'''
# We can also create objects separately
dog = Dog()
cat = Cat()
bear = Bear()
cow = Cow()
animal = Animal()
'''

# The loop iterates over each object.
# Python decides at run-time which speak() method to call, based on the actual object type (Dog, Cat, etc.). 
# This is called dynamic dispatch. 
for am in animals: 
  am.speak()

Output

Dog barks
Cat meows
Bears roar
Cows moo
Animal makes a sound

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Python Generators
Python Inheritance
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment