Code Crafter IT Innovation
Loading...
  • Bansal Computer Center
  • punjabedu.bansalcenter.com

Polymorphism in Python

Definition & Importance

Polymorphism is an Object-Oriented Programming concept that allows the same function, method, or operator to behave differently depending on the object or data type.

What does it mean?

Importance of Polymorphism

Polymorphism is essential to:

Polymorphism in Python

Python supports polymorphism naturally because it is:
- Dynamically typed
- Object-oriented
- Runtime bound

Python does not require any special keyword to implement polymorphism.

Types of Polymorphism

Python implements polymorphism through various mechanisms across different levels of the language.

Built-in Function Polymorphism

A built-in function can work with different data types. For example, len():

print(len("Python"))      # Works on String
print(len([1, 2, 3, 4]))  # Works on List
print(len((10, 20)))      # Works on Tuple

Operator Polymorphism

The same operator performs different operations for different operands. For example, +:

print(5 + 3)                  # Addition
print("Hello " + "World")     # Concatenation
print([1, 2] + [3, 4])        # List Merging

Function Polymorphism

def add(a, b):
    return a + b

print(add(10, 20))            # Numeric addition
print(add("Hi ", "Python"))   # String addition

Method Overriding & Virtual Functions

Method overriding occurs when a child class provides its own implementation of a method already defined in the parent class.

class Animal:
    def sound(self):
        print("Animal makes sound")

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

obj = Dog()
obj.sound() # Method selection is done at runtime

Virtual Functions in Python

In Python, there is no virtual keyword. All non-static methods are virtual by default, meaning their calls are resolved at runtime.

Runtime Polymorphism Using Parent Reference

class Parent:
    def show(self):
        print("Parent show")

class Child(Parent):
    def show(self):
        print("Child show")

p = Child()
p.show() # The method executed depends on the object, not the reference.

Duck Typing

Duck typing is a core concept in Python where the type or the class of an object is less important than the methods it defines. "If it walks like a duck and quacks like a duck, then it must be a duck."

class Dog:
    def speak(self):
        print("Bark")

class Cat:
    def speak(self):
        print("Meow")

def animal_sound(animal):
    animal.speak() # Python checks method presence, not class type

animal_sound(Dog())
animal_sound(Cat())

Note: No inheritance is required for Duck Typing to work.

Method Overloading & Abstract Classes

Python does not support traditional method overloading. However, it can be simulated.

Simulating Overloading

a) Default Arguments:

def add(a, b=0, c=0):
    return a + b + c

b) Variable Arguments:

def add(*nums):
    return sum(nums)

Abstract Base Classes (ABC)

Abstract base classes enforce method implementation in child classes, providing a formal interface.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def area(self):
        return 10 * 5

r = Rectangle()
print(r.area())

Final Summary & Key Points

What Is NOT Polymorphism in Python

Key FeatureDescription
Dynamic TypingTypes are determined at runtime.
Runtime ResolutionMethod calls are resolved when the code runs.
Duck TypingUnique to Python; focuses on behavior over class.
Implicit VirtualAll normal methods act as virtual functions.

Exam-Ready Definition

Polymorphism in Python is the ability of the same function, method, or operator to perform different actions depending on the object or data type at runtime.

What students Say?

Here are the stdudents...

#

Contact Us

Empower your tech dreams with us. Get in touch!

  • #
  • #
  • #
  • #
  • #