Python Inner Classes
An inner class is a class defined inside another class.
It is mainly used when a class is closely related to another class and is not useful on its own.
Inner classes help:
• Organize related code
• Improve readability
• Limit the scope of helper classes
Defining an Inner Class
A class can be declared inside another class just like a method.
Example
Creating a basic inner class:
Accessing an Inner Class from Outside
To use an inner class, you must first create an object of the outer class, then create an object of the inner class using that instance.
Example
Accessing and using an inner class:
Accessing Outer Class Data from an Inner Class
By default, an inner class does not automatically know about the outer class instance.
To access outer class data, pass the outer object explicitly.
Example
Passing the outer class instance:
Practical Use Case of Inner Classes
Inner classes are useful for modeling components that belong to a larger object.
Example
Using an inner class to represent a laptop’s battery:
Using Multiple Inner Classes
An outer class can contain more than one inner class to represent different components.
