SwadhyAI Notes

All Python notes

Python Inner Classes 🏠

Inner Classes

A class defined in another class is known as an inner class or nested class. If an object is created using a class, the object inside the root class can be used. A class can have one or more inner classes.

✨ Creating an Inner Class

python
class Outer:
    def __init__(self):
        print('Outer class constructor')
    
    class Inner:
        def __init__(self):
            print('Inner class constructor')
        
        def show(self):
            print('This is an inner class')

outer = Outer()
inner = outer.Inner()
inner.show()

🤔 Why use Inner Classes?

Inner classes are used to group classes that belong together. This makes the code more readable and maintainable.

  • Logical Grouping: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together.
  • Encapsulation: It allows you to hide the inner class from the outside world.

🎯 Real-World Use Cases

Inner classes are often used in GUI programming (event listeners) or when creating complex data structures where a helper class is needed only within the main class.

✨ Pro Tip

You can create multiple inner classes in a single outer class, and they can interact with each other.