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

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

  • Case Conversion Methods in Python

    Case Conversion Methods in Python (Syntax + Examples) Python provides several built-in string methods to convert text between different cases (uppercase, lowercase, title case, etc.). Below are the key methods with syntax and examples: 1. upper() โ€“ Convert to Uppercase Purpose: Converts all characters in a string to uppercase.Syntax: python string.upper() Examples: python text = “Hello, World!”…

  • re Programs

    The regular expression r’;\s*(.*?);’ is used to find and extract text that is located between two semicolons. In summary, this expression finds a semicolon, then non-greedily captures all characters up to the next semicolon. This is an effective way to extract the middle value from a semicolon-separated string. Title 1 to 25 chars The regular…

  • Top Programming Languages and Tools Developed Using Python

    Python itself is not typically used to develop other programming languages, as it is a high-level language designed for general-purpose programming. However, Python has been used to create domain-specific languages (DSLs), tools for language development, and educational languages. Here are some examples: 1. Hy 2. Coconut Description: A functional programming language that compiles to Python. It adds…

Leave a Reply

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