passing variables as object attributes

Terry Reedy tjreedy at udel.edu
Mon Aug 16 14:03:28 EDT 2010


On 8/16/2010 9:40 AM, Vikas Mahajan wrote:
> Hello to all
> I am new to python.

Hi, welcome to Python.

Hint 1: 'Variable' is a rather loose term with many meanings. Better to 
think in terms of 'name' ('identifier'), which is specifically defined, 
and 'object'.

> I am facing problem to use variables as object attributes.

Your problem is that you have a attribute name stored in a string 
object, rather than being an unquoted literal in the code.

> I have to use loop and dynamically add attributes to a
> object and for this purpose I have to use variables with object names.

You have to use strings with attribute names. Not uncommon

> For example-:
> Let us say object car has an attribute engine, then
> varname = "engine"
> car.varname = "dummy value"

setattr(car, varname, "dummy value")

is the runtime replacement for

car.engine = "dummy value"

Note that 'setattr(car, "engine", "dummy value")' would work but is 
never needed, since if you have the attribute name itself, you just 
write the assignment.

hasattr and getattr are similar.

-- 
Terry Jan Reedy




More information about the Python-list mailing list