Python Inner Classes
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Python Inner Classes

Kishore V


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

Main Container

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

Book belongs to the library

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

Profile username: guest_user

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

Please charge the battery first Battery fully charged Using the Dell laptop

Using Multiple Inner Classes

An outer class can contain more than one inner class to represent different components.

Example: Multiple inner classes inside one class

Photo captured Playing sound

Our website uses cookies to enhance your experience. Learn More
Accept !