Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign same variable name inside __init__() as in dictionary

I have a dictionary that I have defined as follows:

parameters = dict{a=1,b=2,c=3}

Now I have a class which will initialize this dictionary parameters and use the values as:

class test_class:

    def __init__(self,parameters):
        self.a=parameters['a']
        self.b=parameters['b']
        self.c=parameters['c']

The thing is my dictionary has a lot of entries and these entries will change depending upon how I define the dictionary. Is there a way I can loop over names and values over the dictionary inside the init function to assign the values as I have shown?

like image 715
ruskin23 Avatar asked May 24 '26 13:05

ruskin23


1 Answers

You probably want to use setattr in a loop to add new atributes to the class:

class test_class:
    def __init__(self, params):
        for k, v in params.items():
            setattr(self, k, v)

tc = test_class({'a':1, 'b':2, 'c':3})
print(tc.a, tc.b, tc.c)

1 2 3

like image 153
match Avatar answered May 27 '26 04:05

match



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!