Python Inner Classes

🐍 Python Inner Classes — Complete Guide

In Python, a class defined inside another class is called an inner class (or nested class).
Inner classes are useful to group classes logically and hide implementation details.


🔹 1️⃣ Basic Syntax

class Outer:
class Inner:
def greet(self):
print("Hello from Inner class")

# Creating object of inner class
obj = Outer.Inner()
obj.greet() # Hello from Inner class


🔹 2️⃣ Example: Using Inner Class to Organize Code

class University:
def __init__(self, name):
self.name = name

class Department:
def __init__(self, dept_name):
self.dept_name = dept_name

def info(self):
print(f"Department: {self.dept_name}")

# Create objects
uni = University("ABC University")
dept = University.Department("Computer Science")

print(uni.name) # ABC University
dept.info() # Department: Computer Science

Inner class Department is logically part of University but independent.


🔹 3️⃣ Access Outer Class Attributes from Inner Class

class Outer:
def __init__(self, outer_val):
self.outer_val = outer_val

class Inner:
def display(self, outer_instance):
print("Outer Value:", outer_instance.outer_val)

o = Outer(100)
i = Outer.Inner()
i.display(o) # Outer Value: 100

Pass the outer class object to access its attributes inside inner class.


🔹 4️⃣ Inner Classes with Methods

class Car:
def __init__(self, brand):
self.brand = brand

class Engine:
def start(self):
print("Engine started")

c = Car("BMW")
engine = Car.Engine()
engine.start() # Engine started


🔹 5️⃣ Use Cases of Inner Classes

  1. Logical grouping of classes

  2. Encapsulation of helper classes

  3. Avoid cluttering global namespace

  4. Represent has-a relationships

Example: Car has-a EngineEngine can be an inner class.


🔹 6️⃣ Access Outer Class Methods from Inner Class

class Outer:
def __init__(self, value):
self.value = value

class Inner:
def multiply(self, outer_obj, x):
return outer_obj.value * x

outer = Outer(5)
inner = Outer.Inner()
print(inner.multiply(outer, 10)) # 50


🔹 7️⃣ Summary Table

Feature Description
Inner Class Class inside another class
Access Outer Pass outer object to inner class
Use Case Logical grouping, encapsulation
Instantiation Outer.Inner()
Relationship Often represents “has-a”

🔹 Example: Real-Life Inner Class

class Library:
def __init__(self, name):
self.name = name

class Book:
def __init__(self, title, author):
self.title = title
self.author = author

def display(self):
print(f"{self.title} by {self.author}")

book1 = Library.Book("Python 101", "Vipul")
book1.display() # Python 101 by Vipul

Inner class Book is part of Library logically, but you can instantiate it independently.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *