assign a attribute using getattr
Asked Answered
S

2

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?

Straticulate answered 31/1, 2011 at 2:39 Comment(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.Thoroughpaced
D
25

You use setattr() to assign values to attributes.

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

Dominiquedominium answered 31/1, 2011 at 2:43 Comment(2)
Exactly, I was about to post the same thing but was blocked out for answering too fast!Weikert
:-) Never boring here on SO.Dominiquedominium
S
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.

Suggestible answered 31/1, 2011 at 2:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.