Polymorphism in Python: Types with Examples
According to recent statistics, Python is the 3rd most popular programming language in the world. Its widespread use is because of its readability, simplicity, and many other features. One such feature is polymorphism. Polymorphism is used by 95% of developers in their code.
Polymorphism in Python is an effective concept that has many advantages. It allows you to write code that is flexible and reusable. It also allows programmers to make code more efficient by avoiding repetitive code. Developers can use polymorphism to create functions or methods that can operate on various object types.
What is Polymorphism in Python?
Polymorphism is the capability to utilize the same API for various kinds of objects. It helps create programming code that is additionally broad and replicable. For instance, you can create a method that accepts the parameter of any object as an argument. The function has the ability to invoke suitable methods on that object, regardless of the object’s type.
In Python, polymorphism is obtained by means of inheritance and function overriding. Inheritance is the capability of a class to acquire the attributes and procedures of another class. When a class derives from another class, it is said to be a subclass of that class.
The superclass is the class it is derived from. On the other hand, method overriding is the capability of a subclass to modify a function acquired from its superclass. When the function is replaced, the base class’s variation of the function will be invoked in place of the superclass’s version.
Types of Polymorphism in Python
There are two main types of polymorphism in Python.
Overloading
It is when a function has the same name but different signatures. This means that the function can take different types of arguments. For example,
def add(a, b):
return a + b
def add(a, b, c):
return a + b + c
In this example, the add() function has two different signatures. The first signature takes two arguments and the second signature takes three arguments. The compiler will choose the correct version of the function to call based on the number and types of arguments passed to the function.
Overriding
It is when a subclass redefines a method inherited from its superclass. For example,
class Animal:
def speak(self):
print("I am an animal!")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
In this example, the speak() method is overridden in each of the subclasses of Animal. This means that the speak() method will call the appropriate method, depending on the type of object being used. To learn more about these types of polymorphism in Python, you can opt for an in-depth Python course.
Polymorphism With Class
In polymorphism, a class of a single interface or base can illustrate numerous connected classes. Objects of these varied classes can be employed reciprocally by means of their shared interface. This enables code inheritance, adaptability, and scalability in software architecture.
To describe polymorphism with classes, let’s consider an example utilizing a superclass referred to as ‘Shape’ and two subclasses called ‘Circle’ and ‘Rectangle’.
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
In this example, Shape is the shared superclass, and Circle and Rectangle are subclasses acquired from Shape. Every subclass offers its unique area() method execution founded on its particular attributes.
Polymorphism With Inheritance
Polymorphism in inheritance signifies the capacity of entities of distinct subclasses to be considered objects of their mutual superclass. It permits the compatibility and adaptability of employing distinct objects while executing declared methods in the superclass.
To describe polymorphism with inheritance, let’s take an example using a superclass named ‘Animal’ and two subclasses referred to as ‘Dog’ and ‘Cat’.
class Animal:
def sound(self):
pass
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
Here, Animal is the superclass, and Dog and Cat are subclasses that acquire from Animal. Every subclass offers its individual execution of the sound() procedure founded on its precise attributes.
Polymorphism With a Function and Objects
In functions and objects, polymorphism denotes the capability of a single function to be employed for distinct object types. This leads to diverse performances built on the definite object being transferred as a parameter.
To understand this better, let’s examine an instance applying a procedure named ‘display_info()’ and two object classes called ‘Circle’ and ‘Rectangle’.
class Circle:
def __init__(self, radius):
self.radius = radius
def info(self):
return f"Circle with radius {self.radius}"
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def info(self):
return f"Rectangle with width {self.width} and height {self.height}"
def display_info(shape):
print(shape.info())
In this instance, we have two object classes, Circle and Rectangle, each with its unique info() procedure that provides data concerning the shape. The display_info() method receives an object of any shape as a parameter and invokes the info() function on that object to access and present particular details about the shape. This method does not count on a particular kind of object; it can function with any object that has the info() operation declared.
Conclusion
In conclusion, polymorphism in Python is a powerful tool for writing dynamic code that can be extended and customized quickly and easily. By taking advantage of features like overriding or inheritance, developers can help improve the readability of an application as well as its overall performance by reducing repetition and increasing reusability.