+91 81900 98289

Python Inner Classes

This Python Inner Classes lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A class written inside another class is an inner class. It fits a small type that only makes sense together with the outer one.

Build the inner object from the outer __init__ when each course should own its batch. The inner class does not automatically see the outer object.

Start here

Pass the outer values the inner class needs. It does not receive them on its own.

class Course: # a template for objects def __init__(self, topic): # runs when you create the object self.topic = topic # store this on the object self.batch = self.Batch(1) # store this on the object class Batch: # a template for objects def __init__(self, number): # runs when you create the object self.number = number # store this on the object def label(self): # define the function; it runs when you call it return "Batch " + str(self.number) # send this value back to the caller print(Course("Python").batch.label())

A class inside a class

The inner class is reached through the outer class name.

class Course: # a template for objects class Schedule: # a template for objects def __init__(self, hour): # runs when you create the object self.hour = hour # store this on the object print(Course.Schedule(10).hour)

Build it from a method

A method can return an instance of the inner class.

class Course: # a template for objects class Schedule: # a template for objects def __init__(self, hour): # runs when you create the object self.hour = hour # store this on the object def at(self, hour): # define the function; it runs when you call it return self.Schedule(hour) # send this value back to the caller print(Course().at(10).hour)

A function is often enough

Use an inner class when the inner object has several methods. A dictionary is enough for one value.

def schedule(hour): # define the function; it runs when you call it return {"hour": hour} # send this value back to the caller print(schedule(10)["hour"])
Pass the outer values the inner class needs. It does not receive them on its own.