How to Create a Nested Class in Python?

Estimated read time 2 min read

In Python, you can create a nested class by defining a class within the scope of another class. Here’s an example:

class OuterClass:
    class InnerClass:
        def __init__(self, value):
            self.value = value
        
        def display(self):
            print(f"Inner class value: {self.value}")

    def __init__(self, value):
        self.inner = self.InnerClass(value)

    def display(self):
        print("Outer class")
        self.inner.display()

# create an instance of the outer class
outer = OuterClass(42)

# call the display method
outer.display()

In this example, we define an OuterClass that contains an InnerClass. The InnerClass has its own constructor that takes a value, and a display method that prints out the value. The OuterClass also has a constructor that creates an instance of the InnerClass with the provided value, and a display method that calls the display method of the InnerClass.

To create an instance of the outer class, we simply call the constructor and pass in a value. We can then call the display method of the outer class, which in turn calls the display method of the inner class.

Note that you can access the nested class both from within the outer class and from outside it using the dot notation OuterClass.InnerClass.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply