Nearby lessons
111 of 159Python - Inner Classes
- 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.
Example 2: University and Department
Without an existing University object, there is no chance of an existing Department object.
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.
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
Various Syntaxes for Calling Inner Class Methods
The following are the various possible syntaxes for calling the inner class method.
Syntax 1
Syntax 2
Syntax 3
Demo Program-2: Inner Class to Represent Date of Birth
This program stores a Person's date of birth using an inner class.
Explanation
- The
Personclass contains an inner classDob. - Inside the Person constructor,
self.db = self.Dob()creates a Dob object and stores it in the instance variabledb. p.display()prints the name, andx.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.
Explanation
- The
Humanclass contains two inner classes:HeadandBrain. - The constructor creates both inner class objects and stores them in
self.headandself.brain. h.head.talk()andh.brain.think()call the inner class methods through the Human object.
- 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