Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a new class attribute via __dict__?

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 
like image 370
Philipp der Rautenberg Avatar asked Jan 11 '09 11:01

Philipp der Rautenberg


People also ask

What is __ dict __ attribute?

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.

How do you set a class attribute in Python?

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.

What is the meaning of __ dict __ in Python?

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__.

What is the __ dict __ of a class and or instance of a class and what does it contain?

It's a data descriptor object that returns the internal dictionary of attributes for the specific instance.


1 Answers

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 
like image 164
gak Avatar answered Sep 20 '22 04:09

gak