An inner class or nested class is a defined entirely within the body of another class. If an object is created using a class, the object inside the root class can be used. A class can have more than one inner classes, but in general inner classes are avoided.
One of the most useful and powerful features of Python is its ability to nest classes within classes. A nested class is a class defined within another class, and inherits all the variables and methods of the parent class.
Python Programming Bootcamp: Go from zero to hero
Inner class example
Python has inner classes. Inner classes are classes that are defined inside other classes. Inner classes have access to all the members of their outer classes.
Indention is very important when using inner classes. Every inner class should be indented by 4 spaces.
We create a class (Human) with one inner class (Head). An instance is created that calls a method in the inner class:
In the program above we have the inner class Head() which has its own method. An inner class can have both methods and variables. In this example the constructor of the class Human (init) creates a new head object.
Multiple inner classes
You are by no means limited to the number of inner classes, for example this code will work too:
By using inner classes you can make your code even more object orientated. A single object can hold several sub objects. We can use them to add more structure to our programs.
An inner class lets you group classes. They have some advantages over using only distinct classes.
- Inner class has a local scope
- Easy to understand which classes are related
Inner classes (sometimes callled nested classes) are not widely used in Python.
If you are new to Python programming, I highly recommend this book.