bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/Python/Object-Oriented Python
Python•Object-Oriented Python

Python Inner Classes

Overview

An inner class is a class defined inside another class. The inner class can access the properties and methods of the outer class. Inner classes are useful for grouping classes that are only used in one place, making your code more organized.

Example

Create an inner class:

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")

Formula

outer = Outer()
print(outer.name)

Accessing Inner Class from the Outside

To access the inner class, create an object of the outer class, and then create an object of the inner class:

Example

Access the inner class and create an object: class Outer:

def __init__(self):
self.name = "Outer"

class Inner:

def __init__(self):
self.name = "Inner"
def display(self):
print("Hello from inner class")

Formula

outer = Outer()
inner = outer.Inner()

inner.display()

Accessing Outer Class from Inner Class

Inner classes in Python do not automatically have access to the outer class instance. If you want the inner class to access the outer class, you need to pass the outer class instance as a parameter:

Example

Pass the outer class instance to the inner class: 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}")

Formula

outer = Outer()
inner = outer.Inner(outer)

inner.display()

Practical Example

Inner classes are useful for creating helper classes that are only used within the context of the outer class:

Example

Use an inner class to represent a car's engine: class Car:

def __init__(self, brand, model):

Formula

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!")

Formula

car = Car("Toyota", "Corolla")

car.drive() car.engine.start() car.drive()

Multiple Inner Classes

A class can have multiple inner classes:

Example

Create multiple inner classes:

class Computer:

def __init__(self):

Formula

self.cpu = self.CPU()
self.ram = self.RAM()

class CPU:

def process(self):
print("Processing data...")

class RAM:

def store(self):
print("Storing data...")

Formula

computer = Computer()

computer.cpu.process() computer.ram.store()

Previous

Python Encapsulation Code Challenge