Python Intermediate and Advanced

Python Intermediate_004_ Nested Classes

codeaddict 2025. 1. 12. 22:29

When working on Python projects, you might encounter situations where a class needs to contain another class. This is where nested classes can be helpful. In this post, we will understand what nested classes are, when to use them, and how they compare to using two separate classes. Let’s begin with a simple example using two separate classes and then explore how the same functionality can be achieved with nested classes.

Two Separate Classes Example

Let’s take a real-world example of a School and its Students:

# Two separate classes
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f"My name is {self.name}, and I am {self.age} years old."

class School:
    def __init__(self, name):
        self.name = name
        self.students = []

    def add_student(self, student):
        self.students.append(student)

    def display_students(self):
        print(f"Students in {self.name}:")
        for student in self.students:
            print(student.introduce())

# Usage
school = School("Greenwood High")
student1 = Student("Alice", 15)
student2 = Student("Bob", 16)

school.add_student(student1)
school.add_student(student2)
school.display_students()

Output:

Students in Greenwood High:
My name is Alice, and I am 15 years old.
My name is Bob, and I am 16 years old.

How It Works:

  1. We have two separate classes: Student and School.
  2. The School class uses Student objects to store information about its students.
  3. While this approach works well, it creates two separate classes that exist independently in the global namespace.

Nested Classes Example

Now let’s refactor the above example to use a nested class. Here, we’ll define the Student class inside the School class:

# Nested class example
class School:
    def __init__(self, name):
        self.name = name
        self.students = []

    # Define the Student class inside School
    class Student:
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def introduce(self):
            return f"My name is {self.name}, and I am {self.age} years old."

    def add_student(self, name, age):
        # Create a Student object using the nested class
        student = self.Student(name, age)
        self.students.append(student)

    def display_students(self):
        print(f"Students in {self.name}:")
        for student in self.students:
            print(student.introduce())

# Usage
school = School("Greenwood High")
school.add_student("Alice", 15)
school.add_student("Bob", 16)
school.display_students()

Output:

Students in Greenwood High:
My name is Alice, and I am 15 years old.
My name is Bob, and I am 16 years old.

Key Differences Between the Two Approaches

When to Use Nested Classes

Use nested classes when:

  1. Tight Coupling: The inner class (e.g., Student) is only relevant to the outer class (e.g., School).
  2. Encapsulation: You want to hide the inner class from external use to reduce clutter in the global namespace.
  3. Logical Grouping: Grouping related logic together makes your code easier to read and maintain.