Introduction to Classes in Python
First contact with Object-Oriented Programming: what a class is, how to define one, and how to use them to better organize code.
Key Concepts
- What a class is and what it is used for
- The
__init__method and theselfparameter - Instance attributes
- Instance methods
- Instantiating objects
- The special method
__str__
Mandatory Part
1. First class: Student
Create a Student class that represents a student with their basic data.
Attributes:
nameagegrade
Base example:
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
Instantiate at least two objects and access their attributes:
s1 = Student("Ana", 19, 8.5)
print(s1.name)
print(s1.grade)
2. Adding methods
Add an is_passing() method that returns True if the grade is greater than or equal to 5.
def is_passing(self):
return self.grade >= 5
And a __str__ method to display the student in a readable format:
def __str__(self):
return f"{self.name} (Age: {self.age}) - Grade: {self.grade}"
Check that print(s1) shows the expected result.
3. List of objects
Create a list of Student objects and iterate over it:
students = [
Student("Ana", 19, 8.5),
Student("Luis", 20, 4.0),
Student("Marta", 18, 6.0)
]
for s in students:
print(s)
print("Passing:", s.is_passing())
Extra Steps
4. Method to update the grade
Add an update_grade() method that allows changing the grade with built-in validation:
def update_grade(self, new_grade):
if 0 <= new_grade <= 10:
self.grade = new_grade
else:
print("Invalid grade. Must be between 0 and 10.")
5. Integrate the class with the project
If the student management system from previous sessions used dictionaries to represent students, try replacing them with Student objects.
Goal: see in practice what advantages a class offers over a dictionary.