0

What I'd like to accomplish is to set testobj.alpha to .5 in the example below:

class test():
    def __init__(self):
        self.alpha = 0

d = {'alpha' : .5}
testobj = test()

for i in d:
    testobj.i = d[i] #creates a new class member called 'i' instead of setting alpha to .5

As the comment says, in the for loop, a new class member called i is created, rather than setting the existing alpha member to .5

1 Answer 1

3

Use setattr to set attributes dynamically:

for i in d:
    setattr(testobj, i, d[i])

or update the internal attribute dictionary directly (vars will serve as a proxy for the __dict__ attribute):

vars(testobj).update(d) # No (explicit) loop

The latter approach will fail if an object doesn't have the __dict__ attribute (e.g. it was defined with the __slots__ attribute).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.