Exercise
Classes: Learner And Instructor
Objective
Develop a Python program that incorporates a Person class.
Then, create two additional classes, Student and Teacher, that inherit from Person.
The Student class should include a public method GoToClasses which will print "I’m going to class."
The Teacher class should have a public method Explain that prints "Explanation begins". Additionally, it will have a private attribute subject (a string).
The Person class will feature a SetAge method, which allows setting their age (e.g., "20 years old").
The Student class will also have a public method ShowAge which will print "My age is: 20 years old" (or whatever age is set).
Finally, create a separate test class, StudentAndTeacherTest, that will contain the Main method and perform the following:
Create a Person and make it greet (say hello).
Create a Student, set their age to 21, have them greet and display their age.
Create a Teacher, set their age to 30, have them greet and then explain their subject.
Example Python Exercise
Show Python Code
# Base class Person
class Person:
def __init__(self, name):
# Initialize the person's name
self.name = name
def Greet(self):
# Greet method to say hello
print(f"Hello, my name is {self.name}.")
def SetAge(self, age):
# Set the age method
self.age = age
# Derived class Student that inherits from Person
class Student(Person):
def __init__(self, name):
# Initialize the student with a name
super().__init__(name)
def GoToClasses(self):
# Method to print when the student goes to class
print("I’m going to class.")
def ShowAge(self):
# Method to show the student's age
print(f"My age is: {self.age} years old.")
# Derived class Teacher that inherits from Person
class Teacher(Person):
def __init__(self, name, subject):
# Initialize the teacher with a name and subject
super().__init__(name)
self.__subject = subject # Private attribute for subject
def Explain(self):
# Method to explain the subject
print(f"Explanation begins for {self.__subject}.")
def SetSubject(self, subject):
# Method to set the subject for the teacher
self.__subject = subject
# Test class to demonstrate the functionality
class StudentAndTeacherTest:
@staticmethod
def Main():
# Create a Person object and greet
person = Person("John")
person.Greet()
# Create a Student object, set age, greet, and show age
student = Student("Alice")
student.SetAge(21)
student.Greet()
student.ShowAge()
# Create a Teacher object, set age, greet, and explain subject
teacher = Teacher("Mr. Smith", "Mathematics")
teacher.SetAge(30)
teacher.Greet()
teacher.Explain()
# Run the test class
StudentAndTeacherTest.Main()
Output
python person_inheritance.py
Hello, my name is John.
Hello, my name is Alice.
My age is: 21 years old.
Hello, my name is Mr. Smith.
Explanation begins for Mathematics.
Share this Python Exercise