Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign a attribute using getattr

Tags:

python

getattr

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?

like image 774
Alon Gutman Avatar asked Jan 31 '11 02:01

Alon Gutman


People also ask

What does Getattr () and Hasattr method are used for?

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.

What does Getattr () do in python?

The getattr() function returns the value of the specified attribute from the specified object.

How do you set a class attribute in python?

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.


2 Answers

You use setattr() to assign values to attributes.

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

like image 128
payne Avatar answered Oct 10 '22 23:10

payne


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.

like image 33
lunixbochs Avatar answered Oct 10 '22 22:10

lunixbochs