Polymorphism

Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action.


🌀 Polymorphism with Different Data Types

A simple example of polymorphism in Python is the built-in len() function. It works on many different data types, like strings, lists, tuples, and dictionaries, because all these types have a __len__() method that len() knows how to call.

Let’s look at the len() function with different data types:Method Overloading

  • String: The len() function returns the number of characters.Pythonprint(len("hello")) # Output: 5
  • List: It returns the number of elements in the list.Pythonprint(len([1, 2, 3, 4])) # Output: 4
  • Dictionary: It returns the number of key-value pairs.Pythonprint(len({'a': 1, 'b': 2})) # Output: 2

In each case, len() performs a different operation under the hood, but the user-facing call is always the same. This is polymorphism in action.

➕ The Polymorphic + Operator (Operator Overloading)

The + operator is a great example of polymorphism in Python. Its function changes based on the data types it is used with.

  • For Numbers (Integers & Floats): The + operator performs arithmetic addition.Python# Arithmetic addition for integers print(10 + 20) # Output: 30 # Arithmetic addition for floats print(1.5 + 2.5) # Output: 4.0
  • For Strings: The + operator performs string concatenation. It joins two or more strings together to create a new one.Pythonprint("Hello" + " " + "World") # Output: Hello World
  • For Lists and Tuples: The + operator performs concatenation, combining two lists or tuples into a new single list or tuple.Pythonlist1 = [1, 2, 3] list2 = [4, 5, 6] print(list1 + list2) # Output: [1, 2, 3, 4, 5, 6] tuple1 = (10, 20) tuple2 = (30, 40) print(tuple1 + tuple2) # Output: (10, 20, 30, 40)

💡 How It Works

This polymorphic behavior is possible because each data type has a special method called __add__() that the + operator uses. When you write a + b, Python internally calls a.__add__(b). Each class implements this method differently to suit its own data type.

For example, when you add two integers, the int class’s __add__() method performs addition. When you add two strings, the str class’s __add__() method performs concatenation. This allows the same operator to have different meanings, which is the essence of polymorphism.

with User Defined Function Method Overloading

def sum(seq):
    s = 0
    for x in seq:
        s += x
    return s

sum([2, 4, 6, 8])
20
sum((1, 2, 3))
6
sum({3, 5, 7, 9})
24

Similar Posts

  • group() and groups()

    Python re group() and groups() Methods Explained The group() and groups() methods are used with match objects to extract captured groups from regex patterns. They work on the result of re.search(), re.match(), or re.finditer(). group() Method groups() Method Example 1: Basic Group Extraction python import retext = “John Doe, age 30, email: john.doe@email.com”# Pattern with multiple capture groupspattern = r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’///The Pattern: r'(\w+)\s+(\w+),\s+age\s+(\d+),\s+email:\s+([\w.]+@[\w.]+)’Breakdown by Capture…

  • date time modules class55

    In Python, the primary modules for handling dates and times are: 🕰️ Key Built-in Modules 1. datetime This is the most essential module. It provides classes for manipulating dates and times in both simple and complex ways. Class Description Example Usage date A date (year, month, day). date.today() time A time (hour, minute, second, microsecond,…

  • Inheritance in OOP Python: Rectangle & Cuboid Example

    Rectangle Inheritance in OOP Python: Rectangle & Cuboid Example Inheritance in object-oriented programming (OOP) allows a new class (the child class) to inherit properties and methods from an existing class (the parent class). This is a powerful concept for code reusability ♻️ and establishing a logical “is-a” relationship between classes. For instance, a Cuboid is…

  • Method overriding

    Method overriding is a key feature of object-oriented programming (OOP) and inheritance. It allows a subclass (child class) to provide its own specific implementation of a method that is already defined in its superclass (parent class). When a method is called on an object of the child class, the child’s version of the method is…

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

  • re module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

Leave a Reply

Your email address will not be published. Required fields are marked *