Function Polymorphism
- Function polymorphism means that a single function can operate on different types of data and behave appropriately based on the type of the argument(s).
- Python supports function polymorphism through dynamic typing and overloading behavior of built-in and user-defined functions.
Built-in Function Polymorphism
- Python has many built-in functions that demonstrate polymorphism.
- These functions can take different types of inputs and behave accordingly.
- Although len() is a single function, it works with multiple data types by calling each type's special method: __len__() in str, list, tuple, dict, etc.
-
Actually, while the len() function can indeed be used to return the number of characters in a string or the number of elements in a list, its behavior isn't limited to just those data types. The len() function is a built-in Python function that can be applied to any object that supports the concept of "length" or "size".
The len() function is designed to return the length (number of items) of an object. The specific way it calculates the length depends on the type of the object it's operating on. This ability to handle different types of objects is what makes len() polymorphic.
-
The len() function is natively supported for several built-in types:
- Strings: Returns the number of characters in the string.
- Lists: Returns the number of elements in the list.
- Tuples: Returns the number of elements in the tuple.
- Dictionaries: Returns the number of key-value pairs.
- Sets: Returns the number of elements in the set.
User-Defined Function Polymorphism
- You can write your own functions that accept arguments of different types and behave accordingly.
- Here, the function double() behaves differently depending on the input type — it multiplies a number or repeats a string/list
Function Overloading (Simulated)
- Unlike some other languages (e.g., Java or C++), Python does not support traditional function overloading (same function name with different parameter lists). However, you can simulate it using:
- Default parameters
- Variable-length arguments (*args, **kwargs)
- Type checking inside the function