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

  • Negative lookbehind assertion

    A negative lookbehind assertion in Python’s re module is a zero-width assertion that checks if a pattern is not present immediately before the current position. It is written as (?<!…). It’s the opposite of a positive lookbehind and allows you to exclude matches based on what precedes them. Similar to the positive lookbehind, the pattern…

  • Classes and Objects in Python

    Classes and Objects in Python What are Classes and Objects? In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). Real-world Analogy Think of a class as a “cookie cutter” and objects as the “cookies” made from it. The cookie cutter defines the shape, and each cookie is an instance of that shape. 1. Using type() function The type() function returns…

  • Python Exception Handling – Basic Examples

    1. Basic try-except Block python # Basic exception handlingtry: num = int(input(“Enter a number: “)) result = 10 / num print(f”Result: {result}”)except: print(“Something went wrong!”) Example 1: Division with Zero Handling python # Handling division by zero error try: num1 = int(input(“Enter first number: “)) num2 = int(input(“Enter second number: “)) result = num1 /…

  • sqlite3 create table

    The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code. It is particularly popular because SQLite is a serverless database…

  • Various types of data types in python

    ๐Ÿ”ข Numeric Types Used for storing numbers: ๐Ÿ”ก Text Type Used for textual data: ๐Ÿ“ฆ Sequence Types Ordered collections: ๐Ÿ”‘ Mapping Type Used for key-value pairs: ๐Ÿงฎ Set Types Collections of unique elements: โœ… Boolean Type ๐Ÿช™ Binary Types Used to handle binary data: Want to explore examples of each, or dive deeper into when…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

Leave a Reply

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