22.python_polymorphism
22.python_polymorphism
Function Polymorphism
An example of a Python function that can be used on different objects is the
len() function
1.string
Example
For strings len() returns the number of characters
In [1]: x = "Hello World!"
print(len(x))
12
2.Tuple
Example
For tuples len() returns the number of items in the tuple
In [2]: mytuple = ("apple", "banana", "cherry")
print(len(mytuple))
3.Dictionary
Example
For dictionaries len() returns the number of key/value pairs in the dictionary
In [3]: thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(len(thisdict))
Class Polymorphism
Polymorphism is often used in Class methods, where we can have multiple
classes with the same method name.
For example, say we have three classes: Car, Boat, and Plane, and they all have a
method called move()
Example
Different classes with the same method
In [4]: #Create a Car class
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
def move(self):
print("Sail!")
def move(self):
print("Fly!")
Drive!
Sail!
Fly!
def move(self):
print("Move!")
class Car(Vehicle):
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
Ford
Mustang
Move!
Ibiza
Touring 20
Sail!
Boeing
747
Fly!
Child classes inherits the properties and methods from the parent class.
In the example above you can see that the Car class is empty, but it inherits
brand, model, and move() from Vehicle.
The Boat and Plane classes also inherit brand, model, and move() from Vehicle,
but they both override the move() method.
Because of polymorphism we can execute the same method for all classes