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:
- We have two separate classes: Student and School.
- The School class uses Student objects to store information about its students.
- 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:
- Tight Coupling: The inner class (e.g., Student) is only relevant to the outer class (e.g., School).
- Encapsulation: You want to hide the inner class from external use to reduce clutter in the global namespace.
- Logical Grouping: Grouping related logic together makes your code easier to read and maintain.
'Python Intermediate and Advanced' 카테고리의 다른 글
Python Intermediate_006: Decorators in Python (0) | 2025.03.04 |
---|---|
Python Intermediate_005: Type Hinting in Python (0) | 2025.02.08 |
Python Intermediate_005: Working with the Requests Library (3) | 2025.01.04 |
Python Intermediate_004_ Guide to PyYAML (0) | 2024.12.30 |
Python Intermediate_003: Filter Function (0) | 2024.12.23 |