Types of polymorphism in Python

Karen 135 Published: 06/15/2024

Types of polymorphism in Python

I'd be happy to help!

Polymorphism in Python refers to the ability of an object or function to take on multiple forms. There are several types of polymorphism in Python, including:

Method Overriding: This type of polymorphism occurs when a subclass provides a different implementation for a method that is already defined in its superclass. The subclass method has the same name, return type, and number of parameters as the superclass method, but it can perform different actions.

For example:

class Animal:

def sound(self):

print("The animal makes a sound.")

class Dog(Animal):

def sound(self):

print("The dog barks.")

In this example, the Dog class overrides the sound() method of its superclass Animal, providing a different implementation.

Method Overloading: This type of polymorphism occurs when multiple methods with the same name can be invoked by passing different numbers or types of parameters. The correct method to call is determined at runtime based on the number and types of arguments passed.

For example:

class Calculator:

def add(self, x):

print(f"Added {x}")

def add(self, x, y):

print(f"Added {x} and {y}")

In this example, the Calculator class provides two methods with the same name add(), but they differ in the number of parameters. The correct method to call is determined at runtime based on the number of arguments passed.

Operator Overloading: This type of polymorphism occurs when the behavior of an operator (such as +, -, *, etc.) is redefined for a class or object. This allows operators to work with custom classes in a way that's similar to how they work with built-in types like integers or strings.

For example:

class ComplexNumber:

def init(self, real, imag):

self.real = real

self.imaginary = imag

def add(self, other):

return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)

In this example, the ComplexNumber class overloads the + operator to perform addition on complex numbers.

** Duck Typing**: This type of polymorphism occurs when an object can be treated as if it were another type, without being its actual type. In Python, duck typing is achieved through inheritance and polymorphism.

For example:

class Rectangle:

def area(self):

pass

class Square(Rectangle):

def area(self):

return 4 * self.side ** 2

def get_area(obj):

return obj.area()

square = Square(3)

print(get_area(square)) # Output: 36

In this example, the Square class is treated as if it were a Rectangle, even though it's not its actual type. This is achieved through inheritance and polymorphism.

Polymorphic Functions: This type of polymorphism occurs when a function can operate on objects of different types.

For example:

def process_list(obj):

for item in obj:

print(item)

numbers = [1, 2, 3]

strings = ['a', 'b', 'c']

print(process_list(numbers)) # Output: 1, 2, 3

print(process_list(strings)) # Output: a, b, c

In this example, the process_list() function can operate on lists of different types (int and str).

These are some of the main types of polymorphism in Python. Polymorphism allows for more flexibility and expressiveness when writing code, and it's an important aspect of object-oriented programming.

Python polymorphism examples

Here are some Python polymorphism examples:

Example 1: Method Overriding

class Animal:

def sound(self):

print("The animal makes a sound.")

class Dog(Animal):

def sound(self):

print("The dog barks.")

class Cat(Animal):

def sound(self):

print("The cat meows.")

dog = Dog()

cat = Cat()

dog.sound() # Output: The dog barks.

cat.sound() # Output: The cat meows.

Here, the sound method is overridden in both the Dog and Cat classes, but they still inherit from the Animal class. This demonstrates polymorphism.

Example 2: Method Overloading

class Calculator:

def calculate(self, x):

print(f"The result of {x} is {x}.")

def calculate(self, x, y):

print(f"The result of {x} and {y} is {x + y}.")

calculator = Calculator()

calculator.calculate(5) # Output: The result of 5 is 5.

calculator.calculate(5, 3) # Output: The result of 5 and 3 is 8.

Here, the calculate method can take either one or two arguments, depending on which method is called. This demonstrates method overloading.

Example 3: Polymorphic Functions

def greet(animal):

if isinstance(animal, Dog):

print("Woof!")

elif isinstance(animal, Cat):

print("Meow!")

dog = Dog()

cat = Cat()

greet(dog) # Output: Woof!

greet(cat) # Output: Meow!

Here, the greet function can take an instance of either the Dog or Cat class, and respond accordingly. This demonstrates polymorphism.

Example 4: Abstract Classes with Polymorphic Methods

from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod

def area(self):

pass

class Circle(Shape):

def init(self, radius):

self.radius = radius

def area(self):

return 3.14 * (self.radius ** 2)

class Rectangle(Shape):

def init(self, width, height):

self.width = width

self.height = height

def area(self):

return self.width * self.height

shapes = [Circle(5), Rectangle(4, 6)]

for shape in shapes:

print(f"Area of {shape.class.name}: {shape.area()}")

Here, the Shape class is abstract and defines an interface, while the Circle and Rectangle classes implement that interface. The polymorphic method area can be called on instances of either class.

These are just a few examples of Python polymorphism. Polymorphism allows for more flexibility and reusability in your code, which is especially important when working with complex systems or large datasets.