Saltar al contenido
Back to home
Session 08 Python 2025-2026 1º

Inheritance and Encapsulation in Python

Extend the class model with inheritance and encapsulation: reuse code between related classes and control access to an object's internal data.

Key Concepts

  • Inheritance: what it is and why it matters
  • Base class and derived class
  • Method overriding
  • Using super()
  • Encapsulation: private and protected attributes
  • Conventions _attribute and __attribute
  • Getter and setter methods

Mandatory Part

1. Base class: Person

Create a Person class with common attributes and methods.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f"Hi, I'm {self.name} and I'm {self.age} years old."

    def __str__(self):
        return f"Person({self.name}, {self.age})"

Instantiate an object and call introduce().


2. Derived class: Student

Create Student as a child class of Person, adding the grade attribute.

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

    def introduce(self):
        base = super().introduce()
        return f"{base} I'm a student with a grade of {self.grade}."

    def is_passing(self):
        return self.grade >= 5

Verify that Student inherits name and age from Person and that introduce() works correctly.


3. Derived class: Teacher

Create a second child class Teacher with a subject attribute.

class Teacher(Person):
    def __init__(self, name, age, subject):
        super().__init__(name, age)
        self.subject = subject

    def introduce(self):
        base = super().introduce()
        return f"{base} I teach {self.subject}."

Show that Person, Student, and Teacher share the same interface (introduce()), but with different behavior.


4. Basic Encapsulation

Modify Student so that grade becomes a private attribute with built-in validation.

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.__grade = None
        self.set_grade(grade)

    def get_grade(self):
        return self.__grade

    def set_grade(self, value):
        if 0 <= value <= 10:
            self.__grade = value
        else:
            print("Invalid grade. Must be between 0 and 10.")

    def is_passing(self):
        return self.__grade >= 5

    def __str__(self):
        return f"{self.name} - Grade: {self.__grade}"

Test what happens when trying to access s.__grade directly from outside the class.


Extra Steps

5. Polymorphic list

Create a list that mixes Student and Teacher objects and iterate over it calling introduce() on all of them without knowing their specific type.

people = [
    Student("Ana", 19, 8.5),
    Teacher("Prof. García", 40, "Mathematics"),
    Student("Luis", 20, 4.0),
]

for person in people:
    print(person.introduce())

Reflect: why does this work? Introduce the concept of polymorphism in a practical way.


6. Integrate with the project

If the current student management system already uses the Student class from the previous session, refactor it to:

  • Create Person as a base class
  • Make Student inherit from Person
  • Add encapsulation to grade

Goal: apply inheritance to existing code and verify that everything still works.


7. Logic challenge

Create a Classroom class that holds a list of Student objects and exposes the following methods:

  • add_student(student) — adds a student to the list
  • average_grade() — returns the average grade of the class
  • top_student() — returns the student with the highest grade
  • failing_students() — returns a list of students who are not passing

Without using max() or sorted() in the first version.