Top 5 Python Interview Problems on Classes and Objects

9.52K 0 0 0 0

Chapter 2: Create a Student Class with Name, Age, and Grades

🧠 Objective

To learn how to:

  • Define a simple class in Python
  • Use instance variables and the constructor method __init__
  • Create and interact with multiple object instances
  • Implement class methods to encapsulate logic
  • Use __str__() for a readable object representation

This is a foundational interview exercise that assesses whether a candidate understands the basics of object-oriented programming in Python.


📌 Problem Statement

Create a Python class called Student with the following requirements:

  1. Each student should have a name, age, and a list of grades.
  2. Add a method to calculate the average grade.
  3. Add a __str__ method that prints the student in the format:
    "Student(name=John, age=20, avg_grade=88.67)"

🔧 Step-by-Step Implementation


Step 1: Define the Class and Constructor

class Student:

    def __init__(self, name, age, grades):

        self.name = name

        self.age = age

        self.grades = grades

Method

Purpose

__init__

Constructor method used to initialize object attributes

self

Refers to the current instance of the class


Step 2: Add a Method to Calculate Average Grade

    def average_grade(self):

        if not self.grades:

            return 0

        return sum(self.grades) / len(self.grades)

  • Handles empty list cases
  • Returns a float representing the average

Step 3: Add a Readable __str__ Method

    def __str__(self):

        avg = self.average_grade()

        return f"Student(name={self.name}, age={self.age}, avg_grade={avg:.2f})"

This improves debugging and output readability.


Full Working Code

class Student:

    def __init__(self, name, age, grades):

        self.name = name

        self.age = age

        self.grades = grades

 

    def average_grade(self):

        if not self.grades:

            return 0

        return sum(self.grades) / len(self.grades)

 

    def __str__(self):

        avg = self.average_grade()

        return f"Student(name={self.name}, age={self.age}, avg_grade={avg:.2f})"


🧪 Example Usage

student1 = Student("Alice", 20, [88, 76, 92])

student2 = Student("Bob", 22, [90, 85, 87, 91])

student3 = Student("Charlie", 19, [])

 

print(student1)

print(student2)

print(student3)

Output:

Student(name=Alice, age=20, avg_grade=85.33)

Student(name=Bob, age=22, avg_grade=88.25)

Student(name=Charlie, age=19, avg_grade=0.00)


🔍 Testing Edge Cases

Test Case

Input

Output

Student with no grades

Student("Tom", 21, [])

avg_grade=0.00

Negative grades (invalid data)

Student("Mark", 22, [-10, 50])

avg_grade=20.00

Float grades

Student("Eve", 20, [89.5, 91.3])

avg_grade=90.40


📈 Extending the Model

Add Validation (Optional)

def add_grade(self, grade):

    if 0 <= grade <= 100:

        self.grades.append(grade)

    else:

        raise ValueError("Grade must be between 0 and 100")

Add Class Variable to Count Students

class Student:

    count = 0

 

    def __init__(self, name, age, grades):

        Student.count += 1

        ...


Concept Recap Table

Concept

Description

__init__

Special method that initializes new object instances

self

Refers to the object itself

Instance variables

Unique data stored in each object (name, grades, etc)

Class methods

Defined with def inside a class, operate on self

__str__

Built-in method for custom string representation



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.