On Aug 16, 8:40 pm, Vikas Mahajan <vikas.mahaja...@gmail.com> wrote: > Hello to all > > I am new to python. I am facing problem to use variables as object > attributes. I have to use loop and dynamically add attributes to a > object and for this purpose I have to use variables with object names. > > For example-: > Let us say object car has an attribute engine, then > varname = "engine" > car.varname = "dummy value" > is giving me Error: object car does not have attribute varname. > > Please tell me how can I use variables as objects attributes. > > Thanks.
I'm not a python expert, so this may not be accurate For me it is easier to define a class that represent the object, and then set attribute for the object. for example : # define a class with no attribute class Car(): pass # instance the class mycar = Car() # dynamically set attribute to the instance newattr = "engine" setattr(mycar, newattr, "dummy value") # or dynamically set attribute to the Class so every instance will inherit it classattr = "color" setattr(mycar, classattr, "yellow") But as I mention, I'm not an expert so maybe it's not a pythonic way to add attribute to an object. Cheers, -- http://mail.python.org/mailman/listinfo/python-list