FIXED: Dynamically reference variables in object

B

Ben Collier

Hi all,

I know that I can dynamically reference a variable with locals()["i"], for instance, but I'd like to know how to do this with a variable in an object.

If I have an object called "device", with variables called attr1, attr2 .. attr50, how could I dynamically reference these?

It's fairly academic, but I'd like to avoid code duplication.

Thanks,

Ben
 
A

Antoon Pardon

Hi all,

I know that I can dynamically reference a variable with locals()["i"], for instance, but I'd like to know how to do this with a variable in an object.

If I have an object called "device", with variables called attr1, attr2 .. attr50, how could I dynamically reference these?

It's fairly academic, but I'd like to avoid code duplication.

Thanks,

Ben

It looks like you are asking for getattr. getattr(device, "attr1"). However unless you have
specific reasons to use atrributes (what you seem to call variables here), it seems you are
better of using a dictionary. So you could then use: device["attr1"].
 
C

Chris Angelico

I know that I can dynamically reference a variable with locals()["i"], for instance, but I'd like to know how to do this with a variable in an object.

If I have an object called "device", with variables called attr1, attr2 .. attr50, how could I dynamically reference these?

It's fairly academic, but I'd like to avoid code duplication.

Check out the getattr function:

http://docs.python.org/3.5/library/functions.html#getattr

But if you're doing that sort of thing, you may want to consider using
a dictionary instead. :)

ChrisA
 

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,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top