create nested classes in python

Nested classes can be defined as classes within classes. This can be useful in organizing related classes which will be used together. Here's an example:

main.py
class OuterClass:
    def __init__(self):
        self.my_inner_class = self.InnerClass()

    class InnerClass:
        def __init__(self):
            self.inner_value = "I'm inside the InnerClass!"
    
my_outer_class = OuterClass()

print(my_outer_class.my_inner_class.inner_value)
286 chars
12 lines

In this example, we define a class OuterClass which has an inner class InnerClass. InnerClass can only be accessed through an instance of the OuterClass. When we create an instance of OuterClass, we also create an instance of InnerClass through the __init__() function. We can then access InnerClass through my_outer_class.my_inner_class and access the inner_value attribute through my_outer_class.my_inner_class.inner_value.

Nested classes can be useful in making code more organized and compartmentalized. However, care must be taken when working with them to ensure that they are used effectively and efficiently.

gistlibby LogSnag