Python Inner Classes

Python Inner Classes

An Inner Class (or Nested Class) is a class defined entirely within another class.

If an object is only going to be useful inside one specific class, you can nest it. This helps keep classes that are logically related grouped together, increasing encapsulation and making your code more readable.


Creating an Inner Class

To create an inner class, you simply define a class inside the body of an outer class. You instantiate the inner class either inside the outer class's __init__ method, or from the outside using the outer class's object.

Inner Class Example

class Student:
  def __init__(self, name, rollno):
    self.name = name
    self.rollno = rollno
    self.lap = self.Laptop() # Instantiating inner class

def show(self): print(self.name, self.rollno) self.lap.show()

class Laptop: def init(self): self.brand = 'HP' self.cpu = 'i5' self.ram = 8 def show(self): print(self.brand, self.cpu, self.ram)

s1 = Student('Navin', 2)

// Call the show method of the outer class s1.show()


Exercise

?

What is the primary purpose of an inner class?