Inner classes in Python

In this post, we will learn about nested classes or inner classes. Inner classes are also referred to as nested classes.

Let us assume we are working on a recruitment website project. The website has three kinds of users like recruiters, job seekers and admins. One of the ways to handle this in python is to create a outer class say users and then create three inner class named recruiters, jobseekers and admins.

This will help us developing out project code in more object oriented way.

If you are new to Python you may get puzzled about inner classes. But it is very simple. An inner class is defined within another class.  If you define a class inside another class then the nested class that is defined insider another class is called inner class.

Advantages of inner class:

  • Grouping: A logical grouping of classes is useful. Nesting so called inner classes makes the software package more systematic.
  • Encapsulation: Many a times we need to hide the nested class from outside world for encapsulation purpose. Inner class helps us achieving this.
  • Readability: Nothing beats the readability factor of a nicely written code. Nested or inner classes provide better readability.

Simple Code example:

An inner class named InnerClass is defined in the code below.

class OuterClass:

def __init__(self):

class InnerClass:

def greet (self)

Inner classes can be decorated with methods and variables as like any other class. Also there is no limitation how many inner classes can a class have. Inner classes help you in making the code more object oriented.

As you can see in the code below, we have written this code in python using jupyter notebook. We have created a session using the python version 3 of the jupyter notebook.

First a class is defined named outer as below. Then we defined a init method in this class that is taking self as an argument. Inside the init method two properties are defined they are named as name and inner respectively. Then name property is initialized with the name of a person Dhiraj and then inner property is initialized with Inner() class that is defined below.

Now,let us see how a class named Inner is defined inside the Outer class.

The inner class has a method called greet. The greet method takes self as parameter and returns a greeting like how are you. You can access the inner class object inside outer class object using a keyword called self.

Then in the next shell of jupyter notebook we are going to use these outer and inner classes.

As you can see in the image above, we are checking if the name is equal to main. This is because Python has entry point for code execution named main. If we execute a Python script, it is used as the main function provided the __name__ attribute is set to __main__ . Then we created an instance of the class called Outer and the instance name is outer.

We are then printing the name property of the outer object and calling the greet method of inner class using outer class object.

The output is as below, which is expected.

Dhiraj…

How are you?

Real world code example for nested classes:

Now let us discuss a real world problem and implement inner class to solve that problem.

As described at the start lets us work on the recruitment website project. The website has three kinds of users like recruiters, job seekers and admins. One of the ways to handle this in python is to create an outer class named user and then create three inner classes named recruiters, jobseekers and admins. Then code for this is as below.

First a class is defined named User as below. Then we defined an init method in this class that is taking self as an argument. Inside the init method two properties are defined they are named as message, recruiter, jobseeker and admin respectively. Then message property is initialized with the text ‘I am user…’ and then recruiter property is initialized with recruiter class, jobseeker property is initialized with JobSeeker class and admin property is initialised with Admin class.

class User:

def __init__(self):

self.message = ‘I am user…’

self.recruiter = self.Recruiter()

self.jobseeker = self.JobSeeker()

self.admin = self.Admin()

class Recruiter:

def talk(self):

return ‘I am recruiter….’

class JobSeeker:

def talk(self):

return ‘I am jobseeker…’

class Admin:

def talk(self):

return ‘I am admin…’

As you can see in the Image above we are checking if the name is equal to main and then creating an instance of the class called User and the instance name is user.

Then we are printing the message property of the user object and calling the talk method of recruiter class using user class object.

We are then calling the talk method of job seeker class using user class object.

And we are also calling the talk method of admin class using user class object.

Finally we are using four print statements to print the desired output.

The output is as below, which is expected.

I am user…

I am recruiter….

I am jobseeker…

I am admin…

Multilevel Inner Classes:

We already saw the inner classes, there is another concept called multilevel inner classes. In the multilevel inner classes, a class contains the inner class and the first inner class contains another inner class. We can see the structure as below:

class OuterClass:

def print_outer(self):

print(“This is Outer class”)

class FirstLevel_InnerClass:

def print_first_inner(self):

print(“This is first inner class”)

class SecondLevel_InnerClass:

def print_second_inner(self):

print(“This is second inner class”)

Conclusion:

Thus in this post we saw a real world implementation of python inner classes. We also saw how the multilevel inner classes are created. There can be more than two levels of inner classes as well. Python has good support for inner classes. These classes should be used when we want to encapsulate the class which means it is closely related to parent class. I hope you liked it and would like to try it on your own. If you would like to learn more in-depth topics on python , check out this course. Happy Python coding!!

Recent Posts

Menu