Top 5 Python Interview Problems on Classes and Objects

1.14K 0 0 0 0

Chapter 4: Build an Employee Management System with Inheritance

🧠 Objective

To explore:

  • Inheritance in Python classes
  • How to use super() to extend and reuse code
  • Overriding methods from a parent class
  • Combining shared and specialized behaviors

This is a staple interview topic for testing your ability to design scalable and extensible object hierarchies.


📌 Problem Statement

Create a simple Employee Management System using OOP in Python:

  1. Build a base class Employee with common attributes: name, salary
  2. Add a method display() to show details
  3. Create two subclasses:
    • Manager (with additional attribute: department)
    • Developer (with additional attribute: programming_language)
  4. Override the display() method in each subclass to show additional info
  5. Track the total number of employees created using a class variable

🔧 Step-by-Step Implementation


✅ Step 1: Define the Base Class Employee

class Employee:

    total_employees = 0

 

    def __init__(self, name, salary):

        self.name = name

        self.salary = salary

        Employee.total_employees += 1

 

    def display(self):

        return f"Name: {self.name}, Salary: ${self.salary}"


✅ Step 2: Create the Manager Subclass

class Manager(Employee):

    def __init__(self, name, salary, department):

        super().__init__(name, salary)

        self.department = department

 

    def display(self):

        base_info = super().display()

        return f"{base_info}, Department: {self.department}"


✅ Step 3: Create the Developer Subclass

class Developer(Employee):

    def __init__(self, name, salary, programming_language):

        super().__init__(name, salary)

        self.programming_language = programming_language

 

    def display(self):

        base_info = super().display()

        return f"{base_info}, Language: {self.programming_language}"


🧪 Example Usage

emp1 = Manager("Alice", 90000, "Marketing")

emp2 = Developer("Bob", 85000, "Python")

emp3 = Developer("Charlie", 80000, "JavaScript")

 

print(emp1.display())

print(emp2.display())

print(emp3.display())

 

print("Total employees:", Employee.total_employees)


✅ Output:

Name: Alice, Salary: $90000, Department: Marketing

Name: Bob, Salary: $85000, Language: Python

Name: Charlie, Salary: $80000, Language: JavaScript

Total employees: 3


🧠 Class Hierarchy Diagram

             Employee

            /       \

        Manager   Developer

✅ Both Manager and Developer inherit common properties from Employee
✅ Override display() method for specialization


✅ Inheritance vs Composition

Feature

Inheritance

Composition

Structure

IS-A relationship (Manager IS-A Employee)

HAS-A relationship (Company HAS-A Employee)

Reusability

Easy via method override

Flexible but requires delegation

Use Case

Common when behavior is shared

Common when combining unrelated things


✅ Advanced Bonus: Use isinstance()

print(isinstance(emp1, Employee))   # True

print(isinstance(emp1, Developer)) # False

✅ Checks the type hierarchy and inheritance chain.


✅ Summary Table

Concept

Code Example

Description

Inheritance

class SubClass(ParentClass)

Child class inherits methods/attrs

super()

super().__init__(...)

Call parent constructor or method

Method overriding

Define method with same name in child class

Specialize or extend behavior

Class variables

Employee.total_employees

Shared across subclasses



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.