<title>How do you dynamically add dynamic properties of a class in python?</title>
2010-10-19 08:49:20| Category: Technical Articles | Tags: class dynamic add Property Python | report | font Size subscription How do I dynamically add dynamic properties to a class in python? Look at the following example
Class A (object): a = 1 b = 2 def fun1 (self): print ' fun1 ' def fun2 (self): print ' fun2 ' a1 = A () a1.c = 1
Here we define a Class A, and an instance of A1. A1.C = 1 Only increases the properties of the instance rather than increasing the properties of the class. We know that the Python object has a __dict__ property, so we try to do this: SetAttr (a.__dict__, ' d ', 1) will get a bit of an error: TypeError: ' Dictproxy ' object has only Read-only attributes (assign to. d)
What does that mean? In fact, the Python object gets the "__dict__" attribute, actually obtains is not the actual dict, obtains is only a dictproxy. In the source typeobject.c static pygetsetdef type_getsets[] = {{"__name__", (getter) type_name, (setter) Type_set_name, NULL}, {" __bases__ ", (getter) type_get_bases, (setter) type_set_bases, NULL}, {" __module__ ", (getter) Type_module, (setter) Type_ Set_module, null}, {"__dict__", (getter) type_dict, NULL, null}, {"__doc__", (getter) type_get_doc, NULL, null}, {0}}; The acquisition method of the __dict__ corresponding to C. We found the implementation of the Type_dict method static Pyobject *type_dict (Pytypeobject *type, void *context) {if (type->tp_dict = = NULL) {Py_incre F (Py_none); return py_none; } return Pydictproxy_new (type->tp_dict);}
Can see in fact every time get __dict__ familiar, is new a dictproxy.
The correct operation should be: SetAttr (A, ' d ', 1) or setattr (a1.__class__, ' d ', 1)
The implementation can be seen in the Classobject.c method: Static int class_setattr (Pyclassobject *op, Pyobject *name, Pyobject *v), the function will not "__" The Start property automatically goes to Op->tp_dict.
From for notes (Wiz)
How do you dynamically add dynamic properties of a class in python?