Polymorphism in Python, a core concept in Object-Oriented Programming (OOP), refers to
the ability of an object to take on many forms. More specifically, it allows methods with the
same name to behave differently depending on the object that calls them, or for functions
to operate on different types of objects in a way specific to each object's type. This leads to
more flexible, reusable, and maintainable code.
There are several ways polymorphism is demonstrated in Python: Method Overriding
(Polymorphism with Inheritance).
When a subclass provides a specific implementation for a method that is already defined
in its superclass, this is known as method overriding. The method in the subclass has the
same name, parameters, and return type (or compatible types) as the method in the
superclass, allowing objects of different subclasses to respond to the same method call in
their own unique way.
Python
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement abstract 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([Link]())
• Polymorphism with Functions and Objects (Duck Typing):
Python's dynamic nature and "duck typing" philosophy naturally support polymorphism. If
an object "walks like a duck and quacks like a duck," then it's considered a duck. This
means that if multiple classes have methods with the same name, a function can call that
method on objects of those different classes without needing to know their specific types,
as long as they possess the required method.
Python
class Car:
def move(self):
return "Driving a car"
class Boat:
def move(self):
return "Sailing a boat"
class Plane:
def move(self):
return "Flying a plane"
def transport_vehicle(vehicle):
print([Link]())
transport_vehicle(Car())
transport_vehicle(Boat())
transport_vehicle(Plane())
Operator Overloading.
Python allows operators to be overloaded, meaning the same operator can have different
meanings depending on the data types of the operands. For example, the + operator
performs addition for numbers and concatenation for strings and lists.
Python
print(10 + 5)
print("Hello" + " World")
print([1, 2] + [3, 4])
In essence, polymorphism in Python promotes code reusability, flexibility, and extensibility
by enabling a single interface (method name, function call, or operator) to work with
various data types or object classes, each responding in a manner appropriate to its
specific implementation.
Python has a set of keywords that are reserved words that cannot be used as variable
names, function names, or any other identifiers:
Keyword Description
and A logical operator
as To create an alias
assert For debugging
async Define an asynchronous function
await Wait for and get a result from an awaitable
break To break out of a loop
case Pattern in a match statement
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no
matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
match Start a match statement (compare a value against cases)
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To return a list of values from a generator