15

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?

Alon Gutman
  • 865
  • 2
  • 14
  • 22
  • 1
    This is very unsafe. What if someone passes an id= parameter in the URL? They would overwrite existing data. Is this Django or a similar framework? You should use proper form handling to save data. – ironfroggy Jan 31 '11 at 02:48

2 Answers2

25

You use setattr() to assign values to attributes.

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

payne
  • 13,833
  • 5
  • 42
  • 49
10
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.

lunixbochs
  • 21,757
  • 2
  • 39
  • 47