文字列オブジェクトを介してクラス属性を割り当てたいのですが、どうすればよいですか?
例:
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
これには組み込み関数があります。
setattr(test, attr_name, 10)
参照: http://docs.python.org/library/functions.html#setattr
例:
>>> 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