assign a attribute using getattr

9.3k views Asked by At

I try to assign value to attributes of some calss like the following:

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

but get the excption: "can't assign to function call"

how can I change attributes without knowing them at complie time?

2

There are 2 answers

2
payne On

You use setattr() to assign values to attributes.

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

0
lunixbochs On
setattr(model, name, request.get(name))

but I'd recommend saving request data in a dictionary, dedicated class, or accessing it directly - unless you're doing specific metaprogramming/introspection, setattr is often the wrong tool for the job.