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 -- https://mail.python.org/mailman/listinfo/python-list