Polymorphism in Python
Polymorphism means “many forms”. In programming it means that the same function name, method or operator can work in different ways for different types of objects.
Python uses polymorphism in many places, and you have already used it without knowing.
Polymorphism in built-in functions
The len() function works with strings, lists, tuples and dictionaries. It is one function, but it works for many types.
print(len("tutorials"))
print(len([2, 4, 7, 8, 9]))
print(len({"a": 1, "b": 2}))
9
5
2
The + operator is another example. It adds numbers, joins strings and joins lists.
print(5 + 3)
print("Py" + "thon")
print([1, 2] + [3])
8
Python
[1, 2, 3]
Polymorphism with class methods
Two different classes can have a method with the same name. We can then call that method without caring about the class of the object.
class India:
def capital(self):
print("New Delhi is the capital of India.")
class USA:
def capital(self):
print("Washington, D.C. is the capital of USA.")
for country in (India(), USA()):
country.capital()
New Delhi is the capital of India.
Washington, D.C. is the capital of USA.
The two classes are not related, but the loop works because both have a capital() method. This style is called duck typing: “if it walks like a duck and quacks like a duck, it is a duck”. Python only checks that the method exists.
Polymorphism with inheritance
A child class can change a method of the parent class (method overriding). Then the same method call gives different results for different objects.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class Sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class Ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
for bird in (Bird(), Sparrow(), Ostrich()):
bird.intro()
bird.flight()
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Operator overloading
You can decide what an operator does for your own class, by writing a special method. For the + operator the method is __add__().
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
print(Point(1, 2) + Point(3, 4))
(4, 6)
Summary
- Polymorphism lets one name work in different ways for different objects.
- Built-in functions like
len()and operators like+are polymorphic. - Classes with the same method name can be used in the same way (duck typing).
- Child classes can override parent methods.
- Special methods like
__add__()allow operator overloading.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |