Search code examples
pythonclassfor-loopinitialization

How to dynamically add arguments to class initialization?


I have a main class and further classes that are extensions of the main class. The main class has two parameters in its init and each of the child classes also uses these parameters + individual parameters

class Main:
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2

class Child1(Main):
    def __init__(self, var1, var2, **kwargs):
        super().__init__(var1, var2)
        self.__dict__.update(kwargs)
        self.var3 = var3
        self.var4 = var4

class Child2(Main):
    def __init__(self, var1, var2, **kwargs):
        super().__init__(var1, var2)
        self.__dict__.update(kwargs)
        self.var5 = var5

I want to be able to initialize the child classes iteratively by passing actual values such as Child1(var1 = 1, var2 = 2, var3 = 3, var4 = 4) and Child2(var1 = 1, var2 = 2, var5 = 5) but without actually having to type them out manually. Ideally I could iterate over a dictionary that stores the values like this:

my_dict = {'Child1': {'var3': 3, 'var4': 4}, 'Child2': {'var5': 5}}

Note that I only want to pass the class specific variables like this. In the end, I would like to have something like this:

var1 = [1, 2, 3, 4]
var2 = [1, 2]
for x,y, (k,v) in product(var1, var2, my_dict.items()):
    v(var1 = x, var2 = y, $fill missing keyword arguments in here that are specific to child class$)

Solution

  • I was actually able to solve this myself. I was able to use unpacking on my_dict to dynamically fill in the missing arguments.

    **for x,y, (k,v) in product(var1, var2, my_dict.items()):
        v(var1 = x, var2 = y, **v)