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
To learn how to:
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:
🔧 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)
✅ 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 |
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)