ruskin23
ruskin23

Reputation: 155

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?

Upvotes: 3

Views: 36

Answers (1)

match
match

Reputation: 11060

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

Upvotes: 3

Related Questions