...

/

Solution: The Single Responsibility Principle

Solution: The Single Responsibility Principle

Learn how to refactor existing code in accordance with the Single Responsibility Principle.

We'll cover the following...

Solution overview

We have refactored the Student class in the following manner:

Press + to interact
Python 3.10.4
Files
from data import students_data
from classes import Student, SemesterResult, CGPACalculator
if __name__ == "__main__":
# Creating a list of students using students_data
students = []
for student_item in students_data:
# Creating a student instance
student = Student(student_item['ID'], student_item['name'], student_item['major'])
# Appending student results
for result_item in student_item['results']:
# Creating a result instance and adding to student's results
result = SemesterResult(result_item['number'], result_item['gpa'], result_item['ch'])
student.add_semester_result(result)
students.append(student)
# Calculating students' CGPAs
for student in students:
print(
f"student ID: {student.get_id()},",
"CGPA: %0.2f" % (CGPACalculator.calculate(student.get_results()))
)

Code explanation

Our class Student originally handled two different ...