The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
In Python, an inner class (also called a
nested class) is a class defined inside another class. Inner classes are often used when you want to logically group classes that are only used within the context of their enclosing class — similar to
namespacing or encapsulation.
Let’s break it down with examples and explanations:
1. Basic Syntax
class Outer:
class Inner:
def display(self):
print("This is the Inner class")
def show(self):
print("This is the Outer class")
Usage:
obj_outer = Outer()
obj_outer.show()
# Access inner class through outer class
obj_inner = Outer.Inner()
obj_inner.display()
Output:
This is the Outer class
This is the Inner class
2. Why Use Inner Classes
Inner classes are used when:
You want to encapsulate helper classes that are not meant to be used outside the enclosing class.
You want to group related functionality together.
You want to improve code organization and readability.
3. Outer and Inner Relationship
Inner classes can access outer class members via an instance reference.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.address = self.Address("Pune", "Maharashtra")
def show(self):
print(f"Name: {self.name}, Age: {self.age}")
self.address.display()
class Address:
def __init__(self, city, state):
self.city = city
self.state = state
def display(self):
print(f"City: {self.city}, State: {self.state}")
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Let’s break it down with examples and explanations:
1. Basic Syntax
Usage:
Output:
2. Why Use Inner Classes
Inner classes are used when:
3. Outer and Inner Relationship
Inner classes can access outer class members via an instance reference.
Usage:
Output:
Here,
Addressis an inner class — it logically belongs only toPerson.4. Accessing Inner Class from Outside
You can create an instance of the inner class using the outer class name:
5. Real-World Example: Data Encapsulation
Usage:
Output:
6. Summary
Outer.Inner