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?
The only use of Python getattr() function is to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason you you should use getattr() function.
The getattr() function returns the value of the specified attribute from the specified object.
Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.
You use setattr()
to assign values to attributes.
See: http://docs.python.org/library/functions.html#setattr
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With