Python Inner Classes
Python lets you define a class inside another class. This inner class can use the outer class's properties and methods when given an outer object.
When a class is only needed in one place, defining it inside another class keeps related code together and your program better organized.
Example
Define an inner class:
Output: complete Python program
class Outer:
def __init__(self):
self.name = "Outer Class"
class Inner:
def __init__(self):
self.name = "Inner Class"
def display(self):
print("This is the inner class")
outer = Outer()
print(outer.name)
Accessing Inner Class from the Outside
Reaching the inner class from outside takes two steps: first build an object of the outer class, then use it to build an object of the inner class:
Example
Build an inner class object and call its method:
Output: complete Python program
class Outer:
def __init__(self):
self.name = "Outer"
class Inner:
def __init__(self):
self.name = "Inner"
def display(self):
print("Hello from inner class")
outer = Outer()
inner = outer.Inner()
inner.display()
Accessing Outer Class from Inner Class
An inner class object gets no automatic link to an outer class instance.
For that link, hand the outer class instance to the inner class as a parameter:
Example
Give the inner class an outer class instance:
Output: complete Python program
class Outer:
def __init__(self):
self.name = "Emil"
class Inner:
def __init__(self, outer):
self.outer = outer
def display(self):
print(f"Outer class name: {self.outer.name}")
outer = Outer()
inner = outer.Inner(outer)
inner.display()
Practical Example
A common use for an inner class is a helper that only makes sense alongside its outer class:
Example
A car's engine modeled as an inner class:
Output: complete Python program
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
self.engine = self.Engine()
class Engine:
def __init__(self):
self.status = "Off"
def start(self):
self.status = "Running"
print("Engine started")
def stop(self):
self.status = "Off"
print("Engine stopped")
def drive(self):
if self.engine.status == "Running":
print(f"Driving the {self.brand} {self.model}")
else:
print("Start the engine first!")
car = Car("Toyota", "Corolla")
car.drive()
car.engine.start()
car.drive()
Multiple Inner Classes
Nothing limits you to one inner class; a class can hold several:
Example
A class with two inner classes:
Output: complete Python program
class Computer:
def __init__(self):
self.cpu = self.CPU()
self.ram = self.RAM()
class CPU:
def process(self):
print("Processing data...")
class RAM:
def store(self):
print("Storing data...")
computer = Computer()
computer.cpu.process()
computer.ram.store()