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

  • Python Installation Guide: Easy Steps for Windows, macOS, and Linux

    Installing Python is a straightforward process, and it can be done on various operating systems like Windows, macOS, and Linux. Below are step-by-step instructions for installing Python on each platform. 1. Installing Python on Windows Step 1: Download Python Step 2: Run the Installer Step 3: Verify Installation If Python is installed correctly, it will…

  • Password Strength Checker

    python Enhanced Password Strength Checker python import re def is_strong(password): “”” Check if a password is strong based on multiple criteria. Returns (is_valid, message) tuple. “”” # Define criteria and error messages criteria = [ { ‘check’: len(password) >= 8, ‘message’: “at least 8 characters” }, { ‘check’: bool(re.search(r'[A-Z]’, password)), ‘message’: “one uppercase letter (A-Z)”…

  • re.I, re.S, re.X

    Python re Flags: re.I, re.S, re.X Explained Flags modify how regular expressions work. They’re used as optional parameters in re functions like re.search(), re.findall(), etc. 1. re.I or re.IGNORECASE Purpose: Makes the pattern matching case-insensitive Without re.I (Case-sensitive): python import re text = “Hello WORLD hello World” # Case-sensitive search matches = re.findall(r’hello’, text) print(“Case-sensitive:”, matches) # Output: [‘hello’] # Only finds lowercase…

  • Date/Time Objects

    Creating and Manipulating Date/Time Objects in Python 1. Creating Date and Time Objects Creating Date Objects python from datetime import date, time, datetime # Create date objects date1 = date(2023, 12, 25) # Christmas 2023 date2 = date(2024, 1, 1) # New Year 2024 date3 = date(2023, 6, 15) # Random date print(“Date Objects:”) print(f”Christmas:…

  • Indexing and Slicing in Python Lists Read

    Indexing and Slicing in Python Lists Read Indexing and slicing are fundamental operations to access and extract elements from a list in Python. 1. Indexing (Accessing Single Elements) Example 1: Basic Indexing python fruits = [“apple”, “banana”, “cherry”, “date”, “fig”] # Positive indexing print(fruits[0]) # “apple” (1st element) print(fruits[2]) # “cherry” (3rd element) # Negative indexing print(fruits[-1]) # “fig”…

  • Python Nested Lists

    Python Nested Lists: Explanation & Examples A nested list is a list that contains other lists as its elements. They are commonly used to represent matrices, tables, or hierarchical data structures. 1. Basic Nested List Creation python # A simple 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]…

Leave a Reply

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