Search code examples
pythonclassinstancedynamicform

Alternative to __init__


I have a Python class with the following __init__ method:

class MyClass(ParentClass):
    def __init__(self, **kwargs):
        my_list = OrderedDict[
            (1, 'abc'),
            (2, 'def'),
            (3, 'ghi'),
        ]

I wanted to alter my_list with such function:

def process_my_list(self):
    new_list = self.my_list.__class__()
    for index, item in self.my_list.items():
        # process index or item
        new_list[index] = new_item
    self.my_list.clear()
    self.my_list.update(new_list)

I wanted to implement this for alteration of a steps’ list of a form. However, in case of dynamic form every step is separate instance, and thus __init__ is called with every step. As a result, my_list always returns back to its previous state. How can I update this list without it being restored? So far I’ve tried:

  • passing the new list as a variable, but the ParentClass is complicated and this solution became a nightmare,
  • making another attribute, but sooner or later I would have to declare it as a global variable for a whole class,
  • making list of steps a property, but I’m just a beginner and fell in trap of infinite loop

Please help.


Solution

  • If you're looking to make my_list a class attribute:

    class MyClass(ParentClass):
        my_list = OrderedDict([
            (1, 'abc'),
            (2, 'def'),
            (3, 'ghi')
        ])
    
        def __init__(self, **kwargs):
            pass
    
        @classmethod
        def process_my_list(cls):
            new_list = OrderedDict()
            for index, item in cls.my_list.items():
                # process index or item
                new_list[index] = new_item
            cls.my_list = new_list