Skip to main content

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:

Prompt
Write a Python Outer class containing an Inner class. Create an Outer object and print its name.
Output: complete Python program

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:

Prompt
Write a Python Outer class with an Inner class that has a display method. Access the inner class from outside.
Output: complete Python program

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:

Prompt
Write a Python Outer class where the Inner class receives the outer instance and accesses its name property.
Output: complete Python program

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:

Prompt
Write a Python Car class with an inner Engine class that has start/stop methods. The Car's drive method checks engine status.
Output: complete Python program

Multiple Inner Classes

Nothing limits you to one inner class; a class can hold several:

Example

A class with two inner classes:

Prompt
Write a Python Computer class with inner CPU and RAM classes, each with their own methods.
Output: complete Python program