Nearby lessons

111 of 159

Python - Inner Classes

📌 What You Will Learn
  • Understand what an inner class is
  • Know when to use an inner class
  • Create inner class objects using different syntaxes
  • Access inner class methods through the outer class object
  • Understand the relationship between outer and inner class objects

What are Inner Classes?

Sometimes we can declare a class inside another class. Such types of classes are called inner classes.

Without the existence of one type of object, if there is no chance of the existence of another type of object, then we should go for inner classes.

Example 1: Car and Engine

Without an existing Car object, there is no chance of an existing Engine object. Hence, the Engine class should be part of the Car class.

Loading editor…

Example 2: University and Department

Without an existing University object, there is no chance of an existing Department object.

Loading editor…

Example 3: Human and Head

Without an existing Human object, there is no chance of an existing Head object. Hence, Head should be part of Human.

Loading editor…

Important Note

Without an existing outer class object, there is no chance of an existing inner class object.

Hence, the inner class object is always associated with the outer class object.

Demo Program-1: Basic Inner Class

Loading editor…

Various Syntaxes for Calling Inner Class Methods

The following are the various possible syntaxes for calling the inner class method.

Syntax 1

Loading editor…

Syntax 2

Loading editor…

Syntax 3

Loading editor…

Demo Program-2: Inner Class to Represent Date of Birth

This program stores a Person's date of birth using an inner class.

Loading editor…

Explanation

  • The Person class contains an inner class Dob.
  • Inside the Person constructor, self.db = self.Dob() creates a Dob object and stores it in the instance variable db.
  • p.display() prints the name, and x.display() prints the date of birth using the Dob object.

Demo Program-3: Multiple Inner Classes

Inside a class, we can declare any number of inner classes.

Loading editor…

Explanation

  • The Human class contains two inner classes: Head and Brain.
  • The constructor creates both inner class objects and stores them in self.head and self.brain.
  • h.head.talk() and h.brain.think() call the inner class methods through the Human object.
📝 Key Takeaways
  • An inner class is a class declared inside another class
  • Use an inner class when the inner object cannot exist without the outer object
  • An inner class object is always associated with its outer class object
  • Inner class objects are created as o.Inner(), Outer().Inner(), or Outer().Inner().method()
  • A class can contain any number of inner classes

🧠 Test Your Knowledge

9 Questions
Progress: 0 / 9

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.