Understanding Inner Classes: Creating Compositions

Published Aug. 29, 2023, 2:12 a.m.

In this lesson, we will learn about an interesting concept in Python classes called inner classes. These are classes that are defined inside another class. They help us create complex relationships and organized structures.

What are Inner Classes?

An inner class is a class that belongs to another class. It is useful when two objects have a strong connection with each other. If one object depends on another object for its existence, the inner class is a good design choice.

Example 1: House and Room

Let's say we want to model a House that has many Room objects. Each room is an important part of the house, so this is a perfect case for an inner class.

class House:
    def __init__(self, address):
        self.address = address
        self.rooms = []
    
    def add_room(self, room_name):
        room = self.Room(room_name)  # Create an object of inner class Room
        self.rooms.append(room)
    
    class Room:
        def __init__(self, name):
            self.name = name  # Set the room's name

# Making a house
my_house = House("123 Main Street")

# Adding rooms to the house
my_house.add_room("Living Room")
my_house.add_room("Kitchen")

# Showing room names
for room in my_house.rooms:
    print(f"Room Name: {room.name}")

Output:

Room Name: Living Room
Room Name: Kitchen

Example 2: Library and Book

Another example is a Library that contains a collection of Book objects. A book belongs to the library, so this is also a suitable situation for inner classes.

class Library:
    def __init__(self, name):
        self.name = name
        self.books = []
    
    def add_book(self, title, author):
        book = self.Book(title, author)  # Create an object of inner class Book
        self.books.append(book)
    
    class Book:
        def __init__(self, title, author):
            self.title = title  # Set the book's title
            self.author = author  # Set the book's author
    
    def list_books(self):
        for book in self.books:
            print(f"Title: {book.title}, Author: {book.author}")

# Making a library
my_library = Library("City Central Library")

# Adding books to the library
my_library.add_book("The Catcher in the Rye", "J.D. Salinger")
my_library.add_book("To Kill a Mockingbird", "Harper Lee")

# Listing books in the library
my_library.list_books()

Output:

Title: The Catcher in the Rye, Author: J.D. Salinger
Title: To Kill a Mockingbird, Author: Harper Lee

Summary:

Inner classes are a way of encapsulating and structuring our code. They work well in situations where one entity's existence relies on another. By using inner classes, we create a design that reflects real-world relationships, resulting in cleaner code and clearer intentions.