Top 5 Python Interview Problems on Classes and Objects

8.16K 0 0 0 0

Chapter 6: Design a Shape Class Hierarchy Demonstrating Polymorphism

🧠 Objective

This chapter teaches you how to:

  • Use polymorphism in Python OOP
  • Create a base class with common methods
  • Override methods in subclasses to provide specialized behavior
  • Use abstract base classes (optional, advanced)
  • Handle different object types with a single interface

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:

  1. Define a base class Shape with a method area().
  2. Create the following subclasses:
    • Circle (with radius)
    • Rectangle (with width and height)
    • Triangle (with base and height)
  3. Override the area() method in each subclass to return the correct area.
  4. Loop over a list of shapes and print their area using a common interface.

🔧 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()

Back

FAQs


1. What is a class in Python?

A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions) that describe the behavior of the objects.

2. What is the difference between class variables and instance variables?

Class variables are shared across all instances of a class, whereas instance variables are unique to each object.

3. How does __init__() work in a class?

__init__() is the constructor method in Python that gets called automatically when a new object is instantiated.

4. What’s the difference between __str__() and __repr__()?

__str__() returns a user-friendly string representation of the object, while __repr__() returns a more technical, unambiguous string for developers.

5. How is inheritance implemented in Python classes?

Python allows a class to inherit from another using (BaseClassName) syntax. The child class gets access to the parent’s attributes and methods.

6. What is encapsulation in Python?

Encapsulation is restricting direct access to some of an object’s components. This is done using private attributes and getter/setter methods.

7. Can a class in Python have multiple constructors?

Python does not support multiple __init__ methods. However, you can use default arguments or @classmethod to simulate multiple constructors.

8. What is polymorphism in OOP with Python?

Polymorphism allows methods to have the same name but behave differently depending on the class or object calling them

9. How are objects and instances different in Python?

There's no real difference. "Object" and "instance" are often used interchangeably. An object is an instance of a class.