polymorphism
Polymorphism is a concept in object-oriented programming (OOP) that allows objects of different classes to be treated the same. It shifts the focus from data types to behaviors.
Polymorphism enables you to use a single interface to represent different underlying classes. In Python, polymorphism is achieved primarily through duck typing, but you can also implement it through inheritance and method overriding.
Polymorphism enhances flexibility and maintainability by allowing you to write more generic and reusable code.
Examples
Here’s an example of polymorphism through duck typing:
birds.py
class Duck:
def swim(self):
print("The duck is swimming.")
class Albatros:
def swim(self):
print("The albatros is swimming.")
The two classes don’t share a common base class. Because they share the same interface, you can still use them in the same way:
>>> from birds import Duck, Albatros
>>> birds = [Duck(), Albatros()]
>>> for bird in birds:
... bird.swim()
...
The duck is swimming.
The albatros is swimming.
Here’s an example of polymorphism using inheritance and method overriding in Python:
animals.py
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Woof, Woof")
class Cat(Animal):
def speak(self):
print("Meow, Meow")
def make_animal_speak(animal):
animal.speak()
In this example, both Dog
and Cat
are subclasses of Animal
and override the .speak()
method.
You can use instances of these classes the same way:
>>> from animals import Dog, Cat
>>> dog = Dog()
>>> cat = Cat()
>>> make_animal_speak(dog)
Woof, Woof
>>> make_animal_speak(cat)
Meow, Meow
The make_animal_speak()
function demonstrates polymorphism by accepting any animal that inherits from Animal
and calling its .speak()
method, regardless of the specific type of animal.
Related Resources
Tutorial
Python Classes: The Power of Object-Oriented Programming
In this tutorial, you'll learn how to create and use full-featured classes in your Python code. Classes provide a great way to solve complex programming problems by approaching them through models that represent real-world objects.
For additional information on related topics, take a look at the following resources:
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Inheritance and Composition: A Python OOP Guide (Tutorial)
- Duck Typing in Python: Writing Flexible and Decoupled Code (Tutorial)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)