FIXED: Dynamically reference variables in object

Chris Angelico rosuav at gmail.com
Wed Mar 26 13:04:00 CET 2014


On Wed, Mar 26, 2014 at 10:49 PM, Ben Collier <bmcollier at gmail.com> wrote:
> 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



More information about the Python-list mailing list