views:

1272

answers:

2

I want to assign a class attribute via a string object - but how?

Example:

class test(object):
  pass

a = test()
test.value = 5
a.value
# -> 5
test.__dict__['value']
# -> 5

# BUT:
attr_name = 'next_value'

test.__dict__[attr_name] = 10
# -> 'dictproxy' object does not support item assignment
+12  A: 

There is a builtin function for this:

setattr(test, attr_name, 10)

Reference: http://docs.python.org/library/functions.html#setattr

Example:

>>> class a(object): pass
>>> a.__dict__['wut'] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dictproxy' object does not support item assignment
>>> setattr(a, 'wut', 7)
>>> a.wut
7
Gerald Kaszuba
I've changed: inbuit -> builtin
J.F. Sebastian
A: 

you can use the .__setattr__(name, value) method

in your example, you would do:

a.__setattr__('next_value', 10)
rejj
One shouldn't directly call __magic__ methods - they are here as implementation of operators or generic functions. In this case, the idiomatic solution is to use setattr(obj, name, value).
bruno desthuilliers