Dynamically reference variable in object

Ian Kelly ian.g.kelly at gmail.com
Wed Mar 26 17:19:03 EDT 2014


On Mar 26, 2014 5:48 AM, "Ben Collier" <bmcollier at gmail.com> wrote:
>
> Sorry, subject was wrong. Please see below:
>
> On Wednesday, 26 March 2014 11:43:49 UTC, 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.

You want to access object "attributes", not "variables".  You can do this
using the functions getattr and setattr like so:

>>> class Foo(object): pass
...
>>> obj = Foo()
>>> setattr(obj, "x", 42)
>>> print(obj.x)
42
>>> print(getattr(obj, "x"))
42
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140326/4a3e18e8/attachment.html>


More information about the Python-list mailing list