On Mar 26, 2014 5:48 AM, "Ben Collier" <bmcoll...@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
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to