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

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • start(), end(), and span()

    Python re start(), end(), and span() Methods Explained These methods are used with match objects to get the positional information of where a pattern was found in the original string. They work on the result of re.search(), re.match(), or re.finditer(). Methods Overview: Example 1: Basic Position Tracking python import re text = “The quick brown fox jumps over the lazy…

  • 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,…

  • Python Variables: A Complete Guide with Interview Q&A

    Here’s a detailed set of notes on Python variables that you can use to explain the concept to your students. These notes are structured to make it easy for beginners to understand. Python Variables: Notes for Students 1. What is a Variable? 2. Rules for Naming Variables Python has specific rules for naming variables: 3….

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

Leave a Reply

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