Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧠Objective
This chapter teaches you how to:
This problem is a common interview favorite to test how well
you understand method overriding, dynamic dispatch, and interface
consistency.
📌 Problem Statement
Create a class hierarchy for different 2D shapes using
polymorphism:
🔧 Step-by-Step
Implementation
✅ Step 1: Define the Base Class
class
Shape:
def area(self):
raise
NotImplementedError("Subclasses must implement this method")
✅ This ensures all shapes must
define their own area() method.
✅ Step 2: Subclass Circle
import
math
class
Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
✅ Step 3: Subclass Rectangle
class
Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
✅ Step 4: Subclass Triangle
class
Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
🧪 Example Usage with
Polymorphism
shapes
= [
Circle(5),
Rectangle(4, 6),
Triangle(3, 7)
]
for
shape in shapes:
print(f"{shape.__class__.__name__}
Area: {shape.area():.2f}")
✅ Output:
Circle
Area: 78.54
Rectangle
Area: 24.00
Triangle
Area: 10.50
✅ Polymorphism in Action
Object Type |
Method Called |
Output |
Circle(5) |
Circle.area() |
Calculates π × r² |
Rectangle |
Rectangle.area() |
Calculates width × height |
Triangle |
Triangle.area() |
Calculates ½ × base × height |
✅ All objects use the same
method name (area)
✅
But each class provides its own implementation
🔄 Optional: Use Abstract
Base Classes (abc module)
from
abc import ABC, abstractmethod
class
Shape(ABC):
@abstractmethod
def area(self):
pass
✅ Enforces that Shape cannot be
instantiated and requires subclasses to implement area().
✅ Summary Table
Concept |
Purpose |
Inheritance |
Share a common interface (Shape) |
Overriding |
Each shape defines its version of area() |
Polymorphism |
Same method behaves differently based on object type |
Abstract Base Class |
Enforce method implementation |
✅ Real-World Uses of Polymorphism
Domain |
Use Case |
UI components |
Different button styles, same render method |
Payment systems |
Different gateways, same process_payment() |
File systems |
Open .txt, .pdf, .doc with same method |
Game dev |
Enemy, NPC, Player → all have move() |
A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the behavior of the objects.
Class variables are shared across all instances of a class, whereas instance variables are unique to each object.
__init__() is the constructor method in Python that gets called automatically when a new object is instantiated.
__str__() returns a user-friendly string representation of the object, while __repr__() returns a more technical, unambiguous string for developers.
Python allows a class to inherit from another using (BaseClassName) syntax. The child class gets access to the parent’s attributes and methods.
Encapsulation is restricting direct access to some of an object’s components. This is done using private attributes and getter/setter methods.
Python does not support multiple __init__ methods. However, you can use default arguments or @classmethod to simulate multiple constructors.
Polymorphism allows methods to have the same name but behave differently depending on the class or object calling them
There's no real difference. "Object" and "instance" are often used interchangeably. An object is an instance of a class.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)