Polymorphism in Python (original) (raw)

Last Updated : 16 Dec, 2024

Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means “many forms”.

Python’s dynamic typing and duck typing make it inherently polymorphic. Functions, operators and even built-in objects like loops exhibit polymorphic behavior.

**Polymorphism in Built-in Functions

Python’s built-in functions exhibit polymorphism, adapting to various data types.

**Example:

Python `

print(len("Hello")) # String length print(len([1, 2, 3])) # List length

print(max(1, 3, 2)) # Maximum of integers print(max("a", "z", "m")) # Maximum in strings

`

Python determines behavior at runtime, enabling these functions to work across diverse types without explicit type declarations.

Let’s explore polymorphism in detail:

Table of Content

**Polymorphism in Functions

Duck typing enables functions to work with any object regardless of its type.

**Example:

Python `

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

print(add(3, 4)) # Integer addition print(add("Hello, ", "World!")) # String concatenation print(add([1, 2], [3, 4])) # List concatenation

`

Polymorphism in Operators

Operator Overloading

In Python, operators like + behave polymorphically, performing addition, concatenation or merging based on the data type.

**Example:

Python `

print(5 + 10) # Integer addition print("Hello " + "World!") # String concatenation print([1, 2] + [3, 4]) # List concatenation

`

**Polymorphism in OOPs

In OOP, polymorphism allows methods in different classes to share the same name but perform distinct tasks. This is achieved through inheritance and interface design. Polymorphism complements other OOP principles like inheritance (sharing behavior) and encapsulation (hiding complexity) to create robust and modular applications.

**Example:

Python `

class Shape: def area(self): return "Undefined"

class Rectangle(Shape): def init(self, length, width): self.length = length self.width = width

def area(self):
    return self.length * self.width

class Circle(Shape): def init(self, radius): self.radius = radius

def area(self):
    return 3.14 * self.radius ** 2

shapes = [Rectangle(2, 3), Circle(5)] for shape in shapes: print(f"Area: {shape.area()}")

`

**Explanation:

**Types of Polymorphism

**Compile-time Polymorphism

Runtime Polymorphism

Example:

Python `

class Animal: def sound(self): return "Some generic sound"

class Dog(Animal): def sound(self): return "Bark"

class Cat(Animal): def sound(self): return "Meow"

Polymorphic behavior

animals = [Dog(), Cat(), Animal()] for animal in animals: print(animal.sound()) # Calls the overridden method based on the object type

`

Output

Bark Meow Some generic sound

**Explanation: Here, the sound method behaves differently depending on whether the object is a Dog, Cat or Animal and this decision happens at runtime. This dynamic nature makes Python particularly powerful for runtime polymorphism.

**Inheritance Class Polymorphism

Inheritance-based polymorphism occurs when a subclass overrides a method from its parent class, providing a specific implementation. This process of re-implementing a method in the child class is known as **Method Overriding.

**Example:

Python `

class Animal: def sound(self): return "Some generic animal sound"

class Dog(Animal): def sound(self): return "Bark"

class Cat(Animal): def sound(self): return "Meow

`

**Explanation: