What is Polymorphism in Python?
Question Explanation
Polymorphism in Python refers to the ability of different objects to respond to the same method call in different ways. This concept is fundamental in object-oriented programming (OOP) as it promotes flexibility and reusability of code. Interviewers often ask about polymorphism to assess a candidate's understanding of OOP principles and their ability to apply these concepts in real-world scenarios. Understanding polymorphism is crucial as it allows developers to write more generic and reusable code. For example, it facilitates the implementation of functions and methods that can operate on objects of different classes. Common misconceptions include the belief that polymorphism only applies to inheritance when, in fact, it can also be achieved through method overloading and operator overloading. In practical applications, polymorphism is widely used in software design patterns, such as the Strategy pattern and the Observer pattern, enabling developers to create systems that are easier to maintain and extend. Ultimately, a solid grasp of polymorphism is essential for any Python developer, as it enhances code quality and maintainability.
Sample Answers
Example 1: Polymorphism with Method Overriding
In Python, polymorphism is commonly demonstrated through method overriding. This occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. For instance, consider a base class Animal with a method speak(). When we create subclasses like Dog and Cat, they can each implement their version of speak(). Here's a simple example:
class Animal:
def speak(self):
return "Animal speaks"
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())
This code will output:
Woof!
Meow!
Through this example, we see how the same method speak() behaves differently depending on the object type, showcasing the essence of polymorphism.
Example 2: Polymorphism with Function Arguments
Another practical application of polymorphism in Python is through function arguments. You can create functions that accept parameters of different types, allowing for a unified interface. For example, consider a function that calculates the area of shapes. We can define a base class Shape, and derive classes like Circle and Rectangle. Each class can implement its method to calculate the area. Here's how this can be structured:
import math
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * (self.radius ** 2)
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
shapes = [Circle(5), Rectangle(4, 6)]
for shape in shapes:
print(shape.area())
This code will output:
78.53981633974483
24
This demonstrates how a single function call can invoke different methods based on the object type, emphasizing the power of polymorphism.
Example 3: Operator Overloading as Polymorphism
Polymorphism can also be illustrated through operator overloading in Python, enabling custom classes to define behavior for standard operators. For instance, if we create a Vector class, we can overload the + operator to enable vector addition. Here's an example:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f'({self.x}, {self.y})'
v1 = Vector(2, 3)
v2 = Vector(5, 7)
v3 = v1 + v2 # Uses the overloaded + operator
print(v3) # Output: (7, 10)
This example showcases how polymorphism allows us to redefine how operators function with custom objects, enhancing code readability and usability.
Keywords
Ready to practice more questions?
Explore our collection of technical interview questions from top companies.
View All Questions