Polymorphism in Python
Polymorphism in Python
Polymorphism allows a subclass to Python dynamically dispatches the This enables you to write code that
provide its own implementation of appropriate method can work with objects of different
a method that is already defined in implementation at runtime, based classes, as long as they have a
its superclass. on the actual type of the object. common interface.
Polymorphism with Classes
Duck Typing Interfaces
Python's duck typing allows Python doesn't have explicit
objects of different classes to interfaces like some other
be used interchangeably, as languages, but you can
long as they have the required achieve the same effect using
methods and attributes. abstract base classes or duck
typing.
Flexibility Composition
Polymorphism with classes Polymorphism also works well
promotes code reuse and with composition, where
extensibility, as you can write objects can be composed of
functions that work with any other objects that implement
object that implements the the required interface.
required interface.
Polymorphism with Inheritance
Superclass
A superclass defines a common interface that can be
implemented by its subclasses.
Subclasses
Subclasses can override or extend the methods defined
in the superclass, providing their own implementation.
Polymorphism
This allows code to work with objects of any subclass, as
long as they implement the required interface.
Example: Calculating Area
1 Shape Class 2 Subclasses
Define a base class that Create subclasses like
has a common "area" Circle, Rectangle, and
method for calculating Triangle that override the
the area of a shape. "area" method with their
own implementation.
3 Polymorphism
You can now write code that works with any shape object, as
long as it has an "area" method.
Benefits of Polymorphism