Attribution
This page originates from TeachBooks/learn-programming, version: mude-2025
import matplotlib
if not hasattr(matplotlib.RcParams, "_get"):
matplotlib.RcParams._get = dict.get
1.6. Exercise#
Exercise
It is time to practice what you have learned so far about classes, inheritance, and polymorphism. Given the predefined Person class, create a Student and Teacher classes that inherit from People and have the additional following requirements
Create a class Student:
Make class Student inherit class Person;
Add parameters
start yearandGPA gradein the__init__method and reuse the parent constructor for the other attributes;Create a method
change_grade, which sets a new grade for the student;Override the
introduce_yourselfmethod to account for the 2 new fields (start year and GPA grade). In your overriding try to reuse the parentintroduce_yourselfmethod implementation by callingsuper();
Create a class Teacher:
Make class Teacher inherit class Person;
Add an attribute called
studentsof typesetin the__init__method and reuse the parent constructor for the other attributes. Remember that a set is a collection of elements that contains no duplicates. A set can be initialised in multiple ways. For example,my_set = set()ormy_set = {};Create a method
add_student, which adds a student to the student set of a teacher. Elements to a set can be added using the methodadd(). For example,my_set.add(3);Create a method
print_classroom, which prints the introductions of all the students in the classroom of the teacher. (Hint: callintroduce_yourselfon every Student object in the set).
Similarly to the previous exercise, show your new classes are working properly by creating objects for each of them and calling their respective methods. Furthermore, add the necessary documentation for the classes and methods.
class Person():
def __init__(self, name, age, country_of_origin):
"""Constructor to initialise a Person object.
Keyword arguments:
name -- the name of the person
age -- the age of the person
country_of_origin -- the country the person was born
"""
self.__name = name
self.age = age
self.country_of_origin = country_of_origin
def introduce_yourself(self):
"""Prints a brief introduction of the person."""
print(f"Hello, my name is {self.__name}, I am {self.age} and I am from {self.country_of_origin}.")
def get_name(self):
"""Gets the name of a person."""
return self.__name
"""Use this code cell to type your answer."""
Tip
If you have done the exercise correctly, Something like the following output should be printed when your run the following code:
print("Showing how class Student is defined:")
student = Student("Mike", 22, "Italy", "2021", 7.3)
student.change_grade(7.2)
print(f"New GPA grade of student is {student.gpa_grade}.")
print()
print("Showing how class Teacher is defined:")
teacher = Teacher("Joe", 42, "Germany")
teacher.introduce_yourself()
teacher.add_student(student)
teacher.print_classroom()
Showing how class Student is defined:
New GPA grade of student is 7.2.
Showing how class Teacher is defined:
Hello, my name is Joe, I am 42 and I am from Germany.
The classroom consists of the following students:
Hello, my name is Mike, I am 22 and I am from Italy.
My GPA grade is 7.2 and I started studying in year 2021.
Solution to Exercise
class Student(Person):
def __init__(self, name, age, country_of_origin, start_year, gpa_grade):
"""Constructor to initialise a Student object.
Keyword arguments:
name -- the name of the student
age -- the age of the student
country_of_origin -- the country the student was born
start_year -- the year the education of the student began
gpa_grade -- current gpa_grade of a student
"""
super().__init__(name, age, country_of_origin)
self.start_year = start_year
self.gpa_grade = gpa_grade
def introduce_yourself(self):
"""Prints a brief introduction of the student."""
super().introduce_yourself()
print(f"My GPA grade is {self.gpa_grade} and I started studying in year {self.start_year}.")
def change_grade(self, new_grade):
"""Modifies current GPA grade of the student."""
self.gpa_grade = new_grade
class Teacher(Person):
def __init__(self, name, age, country_of_origin):
"""Constructor to initialise a Teacher object.
Keyword arguments:
name -- the name of the teacher
age -- the age of the teacher
country_of_origin -- the country the teacher was born
"""
super().__init__(name, age, country_of_origin)
self.students = set()
def add_student(self, student):
"""Adds a student to the classroom of a teacher.
Keyword arguments:
studnet -- student to add to the classroom
"""
self.students.add(student)
def print_classroom(self):
"""Prints the classroom of a teacher."""
print("The classroom consists of the following students:")
for student in self.students:
student.introduce_yourself()
print("Showing how class Student is defined:")
student = Student("Mike", 22, "Italy", "2021", 7.3)
student.change_grade(7.2)
print(f"New GPA grade of student is {student.gpa_grade}.")
print()
print("Showing how class Teacher is defined:")
teacher = Teacher("Joe", 42, "Germany")
teacher.introduce_yourself()
teacher.add_student(student)
teacher.print_classroom()