Table of Contents
Introduction To Polymorphism in Python
Polymorphism in Python means the same meaning having different forms. In a programming language, polymorphism means it refers to the single type of entity or function to represent different types. Is a concept of Object-Oriented Programming language. Polymorphism interfaces use different data types, different classes, or different inputs.
Protocols are polymorphic functions that are embedded into python language.
Some important protocols:
- __add__
- __contains__
- __iter__
__add__
Addition operation using this function,
>>> 2+3
5
>>> two = 2
>>> two.__add__(4)
6
>>> ‘2’ + ‘3’
‘23’
>>> ‘2’.__add__ (‘3’)
‘23’
__contain__
It is a built-in protocol.
For example:
When the interpreter encounters ‘x’ in [‘x’,‘y’] it means that __contains__ function on the object to the right of in and pass it the object to the left side of in as a parameter.
>>> 'y' in ['x', 'y']
True
>>> 'y' in ('x', 'y')
True
>>> 'y' in {'x', 'y'}
True
Using __contains__:
>>> ['x', 'y'].__contains__('y')
True
>>> ('x', 'y').__contains__('y')
True
>>> {'x', 'y'}.__contains__('y')
True
__iter__
How many iterations in implemented in python.
For example,
>>> number = [1,2,3,4,5]
>>> for i in [1,2,3,4,5]:
... print(i)
...
1
2
3
4
5
Using __iter__
>>> itr_obj = [1,2,3].__iter__()
>>> type(itr_obj)
<class 'list_iterator'>
>>> itr_obj.__next__()
1
>>> itr_obj.__next__()
2
>>> itr_obj.__next__()
3
>>> itr_obj.__next__()
raceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Polymorphism function in Python
Some important function in python which are comfortable to run the different data types.
len() function:
a = ‘fireblaze’
print(len(a))
9
print(len(["Fireblaze ", "AI", "School"]))
3
The above example shows various data types such as list, string, tuple, set, and dictionary every function can work with len().
Polymorphism and Inheritance
Same as another programming language, a child classes in Python also inheritance and attributes from the parent class know as “Method Overriding”.
The advantage in polymorphism is allowed to access this overridden method and attribute that have the same name as the parent class.
class Parent(object):
def __init__(self):
self.value = 5
def get_value(self):
return self.value
class Child(Parent):
def get_value(self):
return self.value + 10
Output:
>>> c = Child()
>>> c.get_value()
15