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
A special attribute of every module is __dict__. This is the dictionary containing the module's symbol table. object.__dict__ A dictionary or other mapping object used to store an object's (writable) attributes.
Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.
The __dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects. To put it simply, every object in Python has an attribute that is denoted by __dict__.
It's a data descriptor object that returns the internal dictionary of attributes for the specific instance.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With