bhylu.com

Advertisements

Python Inner Classes

A class can be defined inside another class to organise a closely related type. It does not automatically receive access to an outer instance.

Understand the idea

The nested class is an attribute of its containing class and can be constructed explicitly. If it needs an outer object's data, pass that data or a reference deliberately. A nested class can be helpful for namespacing a small result type, but a module-level class is often easier to import, type-check, and reuse.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

class Workshop:
    class Ticket:
        def __init__(self, code):
            self.code = code

ticket = Workshop.Ticket("BK-2048")
print(ticket.code)

Read the result

The output is BK-2048. No Workshop instance was required to construct the ticket.

Try one change

Pass an event title into Ticket explicitly and compare that design with a separate module-level Ticket class.