Nested classes
Theory
Machine translation, not yet reviewed by a native speaker.
A class can be declared inside another class:
class Car:
class Engine:
def __init__(self, power):
self.power = power
def start(self):
return f"{self.power} hp engine started"
def __init__(self, model, power):
self.model = model
self.engine = Car.Engine(power)
car = Car("Camry", 180)
car.engine.start() # '180 hp engine started'
A nested class is simply a class whose name is "tucked away" inside the outer one: Car.Engine. It has no special link to the outer object — Engine doesn't see a particular car's attributes unless you pass them explicitly.
When it fits: a helper class is needed only by the outer one and makes no sense outside it. For example, Meta in Django models is a nested class with settings:
class Course(models.Model):
title = models.CharField(max_length=200)
class Meta:
ordering = ["title"]
When it's better not to: in most cases an ordinary class next to it at module level reads more easily and is easier to test. If a nested class grows or someone else needs it, move it out.
The relationship "a car contains an engine", as in the example above, is called composition. It's a common alternative to inheritance.