passing variables as object attributes

V

Vikas Mahajan

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.
 
M

misterdi

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top