Python Tutorials · Python Classes

Python Inner Classes

Learn all about Python Inner Classes in this comprehensive tutorial.

5 min read beginner
  • An inner class is a class defined inside another class.
  • To access the inner class, create an object of the outer class, and then create an object of the inner class:
  • Inner classes in Python do not automatically have access to the outer class instance.
  • Inner classes are useful for creating helper classes that are only used within the context of the outer class:
  • A class can have multiple inner classes:

Python Inner Classes

An inner class is a class defined inside another class. The inner class can access the properties and methods of the outer class.

Inner classes are useful for grouping classes that are only used in one place, making your code more organized.

python

Accessing Inner Class from the Outside

To access the inner class, create an object of the outer class, and then create an object of the inner class:

python

Accessing Outer Class from Inner Class

Inner classes in Python do not automatically have access to the outer class instance.

If you want the inner class to access the outer class, you need to pass the outer class instance as a parameter:

python

Practical Example

Inner classes are useful for creating helper classes that are only used within the context of the outer class:

python

Multiple Inner Classes

A class can have multiple inner classes:

python

Module quiz

2 questions
1

Which of the following is true about Python Inner Classes?

2

What is the most common pitfall when working with Python Inner Classes?

Answer all questions to submit.