Junior
What is polymorphism in the context of programming?
sobes.tech AI
Answer from AI
Polymorphism is a concept that allows working with objects of different classes through a common interface. In Python, this is mainly implemented through "duck typing" and inheritance.
Duck Typing:
If an object can perform the required operations (it has the necessary methods and attributes), then its specific type does not matter.
# Example of duck typing
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
def make_sound(animal):
return animal.speak()
# Although Dog and Cat are different classes, make_sound works with both
dog = Dog()
cat = Cat()
print(make_sound(dog))
print(make_sound(cat))
Polymorphism through inheritance:
Subclasses can override methods of the parent class, providing their specific implementation.
# Example of polymorphism through inheritance
class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def make_sound(animal):
return animal.speak()
# Objects of different subclasses call their own version of speak()
dog = Dog()
cat = Cat()
print(make_sound(dog))
print(make_sound(cat))
Advantages:
- Simplifies code, making it more flexible and readable.
- Allows working with collections of heterogeneous objects uniformly.
- Facilitates system extension with new types without modifying existing code.
Examples in Python's standard library:
- Built-in functions like
len(),iter(),str()work with different data types. - Operators (e.g.,
+for addition of numbers, string concatenation, list merging).