The concept of polymorphism in OOP requires that different objects can be treated as objects of a common parent class. More simply, the idea of polymorphism is that there is a single interfaces to entities of different types, or a single symbol to represent multiple types.
class Dog:
def speak(self):
print("Woof")
class Cat:
def speak(self):
print("Meow")
animal_list = [Dog(), Cat()]
for animal in animal_list:
animal.speak()https://www.bmc.com/blogs/polymorphism-programming/
Subtype polymorphism
This type of polymorphism use a single class name to different to multiple types of subtypes at the same time. For example, we might have a Car class that is the superclass of Fiat, Subaru, etc. In any function or program we can substitute the specific subtype with Car itself and it should continue to work.
class Car:
def __init__(self, color):
self.color = color
def get_color(self):
return self.color
class Fiat(Car):
pass
class Subaru(Car):
pass
fiat = Fiat("white")
subaru = Subaru("black")
def get_color(car: Car):
print(car.color)
get_color(fiat)
get_color(subaru)Parametric polymorphism
This type of polymorphism provides a way to use one function to interact with multiple types. For example, given a list of types, we can use the same functions regardless of the type itself:
item_list = [Car(), Dog(), Food()]
for item in item_list:
item_list.remove(item)Here each of the specific types in the class might be different, but we can interact with all of them using the same interface of a list.
Question
This seems a bit far fetched, since what we are interacting with is a
list, which is its own type, rather than the elements of that list.