0

I would like to create attributes of an object based on a dictionary passed in as an argument. Here is the code. But it does not work as

class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for k in di.keys():
            name = 'k' + '_' + 'series'
            self.name = None

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series 

I get the following error: 'Obj' object has no attribute 'c'

The code read "name" as a literal, and not as the variable defined.

0

2 Answers 2

2

Use setattr

class Obj(object):
    def __init__(self, di):
        for key, value in di.items():
            setattr(self, key, value)

Some additional advice:

Your code is very strange. I'm not sure why you expect self.name to evaluate as self.(eval('name')) when that clearly doens't happen elsewhere in python

 lower = str.upper
 str.lower('Hello')  # -> still returns 'hello'

There is no need to iterate over dictionary.keys(), especially in python 2. for k in dictionary: works just fine. If you want both keys and values use dictionary.items() (or dictionary.iteritems() in python 2).

name = 'k' + '_' + 'series' just makes the string 'k_series'. You need to be able to tell the difference between a string and a variable name. I think you mean k + '_' + series but series is never defined. Don't use + to concatenate strings like that anyway, use .format.

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

2 Comments

This will not add attributes c_series and d_series to the object
No but I think the person asking the question should be able to figure that out. Just giving them the answer without explaining why does not help them!
0

This is what will work :

class Obj(object):
    def __init__(self, di):
        self.a = 0
        self.b = 1
        for key, value in di.items():
            key += '_series'
            setattr(self, key, value)

di = {'c':0,'d':1}
Obj_instance = Obj(di)
print Obj_instance.c_series

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.