FIXED: Dynamically reference variables in object

Antoon Pardon antoon.pardon at
Wed Mar 26 12:59:30 CET 2014

On 26-03-14 12:49, Ben Collier wrote:
> 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"].

Antoon Pardon

More information about the Python-list mailing list