Assign attribute using getattr

I am trying to assign a value to the attributes of some calss for example:

for name in dir(modelType): if request.get(name): getattr(model, name) = request.get(name) 

but we get an exception: "cannot assign a function call"

How can I change attributes without knowing them at the appropriate time?

+8
python getattr
source share
2 answers

You use setattr() to assign values ​​to attributes.

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

+13
source share
 setattr(model, name, request.get(name)) 

but I would recommend storing the request data in a dictionary, a dedicated class, or accessing it directly - unless you are doing specific metaprogramming / introspection, setattr is often the wrong tool to work with.

+5
source share

All Articles