Can you list the types of polymorphism used in Python?
sobes.tech AI
Answer from AI
The following types of polymorphism are used in Python:
-
Subtype polymorphism (inheritance) — objects of different classes related by inheritance can be used through a common interface. For example, different subclasses implement the same method with different logic.
-
Parameter polymorphism (function overloading) — Python does not have classical overloading by types, but you can implement functions that accept different types of arguments and behave differently (dynamic typing).
-
Inclusion polymorphism (duck typing) — an object is considered suitable if it has the necessary methods or properties, regardless of its class. For example, if an object "quacks" and "swims", it can be considered a duck.
Example of duck typing:
class Duck:
def quack(self):
print("Quack")
class Person:
def quack(self):
print("I can quack like a duck")
def make_it_quack(duckish):
duckish.quack()
make_it_quack(Duck()) # Quack
make_it_quack(Person()) # I can quack like a duck
Thus, polymorphism in Python is based on the flexibility of dynamic typing and inheritance.