Exercice 42

  1. Create a Python class Person with attributes: name and age of type string.
  2. Create a display() method that displays the name and age of an object created via the Person class.
  3. Create a child class Student  which inherits from the Person class and which also has a section attribute.
  4. Create a method displayStudent() that displays the name, age and section of an object created via the Student class.
  5. Create a student object via an instantiation on the Student class and then test the displayStudent method.

Solution:

class Person:
# define constructor with name and age as parameters
def __init__(self, name, age):
self.name = name
self.age = age
# create display method fro Person class
def display(self):
print("Person name : ", self.name)
print("Person age = ", self.age)

# create child class Student of Person class
class Student(Person):
# define constructor of Student class with section additional parameters
def __init__(self, name , age , section):
Person.__init__(self,name, age)
self.section = section

# Create display method for Student class
def displayStudent(self):
print("Student name : ", self.name)
print("Student age = ", self.age)
print("Student section = ", self.section)

# Testing Person class
P = Person("Tomas Wild", 37)
P.display()
print("-------------------------------")
S = Student("Albert", 23 , "Mathematics")
S.displayStudent()

The output is as follow:
Person name :  Tomas Wild
Person age =  37
-------------------------------
Student name :  Albert
Student age =  23
Student section =  Mathematics

Younes Derfoufi
my-courses.net

Leave a Reply