Joop
Joop

Reputation: 8108

Setting class instance variables from dictionary or list

Setting Instance variables

I have two lists:

var_names = ['var1',  'var2', 'var3']
var_values = [1, 2, 3]

Could also be dict:

dict = {'var1': 1, 'var2':2, 'var3':3}

I am actually getting them from pandas, but getting from there to dict is generic and easy.

These list of instance variables have changing length but as part of the instantiation of a class i want to add them to the instance variables. E.g. for lists given above

self.var1 = var_values[0]
self.var2 = var_values[1]
self.var3 = var_values[2]

Could have similar code if the variable names and values were in a dict. Think i used setattr about a year ago, but I cant figure it out now. Any pointers. Just getting to junk using search

Upvotes: 2

Views: 738

Answers (2)

Kuishi
Kuishi

Reputation: 157

This code should work in python 3:

class testclass(object):
    # constructor
    def __init__(self, inputdict):

        # iterate through dictionary
        for key, value in inputdict.items():
            self.__setattr__(key, value) 

# usage
test = testclass({'key1': 1})
print(test.key1)

But I'm not sure why you should need something like this. You can't be sure if a certain attribute really exists.

In my opinion a construction with an internal dictionary and a getter-method would be something more easy to handle.

[EDIT] Typo

Upvotes: 2

isedev
isedev

Reputation: 19601

You are looking for this I believe:

self.__dict__.update(zip(var_names,var_values))

You could also use itertools.izip to gain in efficiency (by avoiding the creation of the temporary list returned by zip).

Upvotes: 6

Related Questions