Home >Backend Development >Python Tutorial >How to Use Polymorphism in Python?
This article explains Python's polymorphism, achieved through inheritance and duck typing. It details how different classes can share a common interface, enabling flexible code reuse and improved maintainability. Examples illustrate how polymorphis
Polymorphism in Python, like in other object-oriented programming languages, allows objects of different classes to be treated as objects of a common type. This is achieved primarily through inheritance and duck typing.
Using Inheritance: You define a base class with a method (or methods). Then, you create derived classes that inherit from the base class and override the method(s) to provide specific implementations. When you call the method on an object, Python will use the implementation defined in the object's class. This is called runtime polymorphism because the specific method called is determined at runtime based on the object's type.
<code class="python">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!" animals = [Dog(), Cat()] for animal in animals: print(animal.speak()) # Output: Woof! Meow!</code>
Using Duck Typing: Duck typing is a more flexible approach. It relies on the principle: "If it walks like a duck and quacks like a duck, then it must be a duck." You don't need explicit inheritance; if an object has the necessary methods, it can be used polymorphically. This is often combined with interfaces or abstract base classes (ABCs) for better structure, but isn't strictly required.
<code class="python">class Bird: def fly(self): print("I'm flying!") class Airplane: def fly(self): print("I'm an airplane flying!") things_that_fly = [Bird(), Airplane()] for thing in things_that_fly: thing.fly() # Output: I'm flying! I'm an airplane flying!</code>
In both examples, the speak
and fly
methods are polymorphic. The specific behavior depends on the object's type, not its class explicitly declared in a variable.
Polymorphism offers several key advantages in Python development:
Polymorphism significantly enhances code readability and maintainability by:
Let's imagine a simple shape-drawing application. We can use polymorphism to handle different shapes without needing separate drawing functions for each:
<code class="python">import math class Shape: def area(self): raise NotImplementedError("Subclasses must implement this method") def perimeter(self): raise NotImplementedError("Subclasses must implement this method") class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius**2 def perimeter(self): return 2 * math.pi * self.radius class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width self.height) shapes = [Circle(5), Rectangle(4, 6)] for shape in shapes: print(f"Area: {shape.area()}, Perimeter: {shape.perimeter()}")</code>
This example showcases polymorphism through inheritance. The area
and perimeter
methods are polymorphic; the correct implementation is called depending on the type of shape object. Adding new shapes (e.g., Triangle, Square) would only require creating a new class inheriting from Shape
and implementing the abstract methods, without needing to change the main loop. This demonstrates the extensibility and maintainability benefits of polymorphism.
The above is the detailed content of How to Use Polymorphism in Python?. For more information, please follow other related articles on the PHP Chinese website!