python logo


Tag: inner class

python inner class

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.

Related Course:
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:

#!/usr/bin/env python

class Human:

def __init__(self):
self.name = 'Guido'
self.head = self.Head()

class Head:
def talk(self):
return 'talking...'

if __name__ == '__main__':
guido = Human()
print(guido.name)
print(guido.head.talk())

Output:

Guido
talking...

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:

#!/usr/bin/env python

class Human:

def __init__(self):
self.name = 'Guido'
self.head = self.Head()
self.brain = self.Brain()

class Head:
def talk(self):
return 'talking...'

class Brain:
def think(self):
return 'thinking...'

if __name__ == '__main__':
guido = Human()
print(guido.name)
print(guido.head.talk())
print(guido.brain.think())

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.

Why inner class?

An inner class lets you group classes. They have some advantages over using only distinct classes.

  1. Inner class has a local scope
  2. 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.

Download Exercises