nested class collectioin in python

To create a nested collection of classes in Python, you can use a dictionary to store instances of the outer class as values. Then, you can create instances of the nested class and add them to the outer class instances.

Here's an example:

main.py
class InnerClass:
    def __init__(self, value):
        self.value = value

class OuterClass:
    def __init__(self):
        self.collection = {}

    def add_inner(self, key, value):
        self.collection[key] = InnerClass(value)
235 chars
11 lines

In this example, we define two classes - InnerClass and OuterClass. InnerClass has an attribute value, and OuterClass has a dictionary collection for storing instances of InnerClass.

To add instances of InnerClass, we can use the add_inner method of OuterClass. It takes a key and a value parameter. The key is used as the key in the collection dictionary, and value is used as the value attribute of the new InnerClass instance.

Here's an example of how to use this code:

main.py
outer = OuterClass()
outer.add_inner("one", 1)
outer.add_inner("two", 2)

print(outer.collection["one"].value)  # Output: 1
print(outer.collection["two"].value)  # Output: 2
174 chars
7 lines

In this example, we create an instance of OuterClass, and add two instances of InnerClass with keys "one" and "two". We then print the value attribute of each instance, which outputs 1 and 2, respectively.

gistlibby LogSnag