2

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

2 Answers 2

6

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).

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.