Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #69143

Re: Dynamically reference variable in object

References <d9daaeb5-04ef-43e8-b60e-3c4ba5790a9d@googlegroups.com> <cddebac0-8d5d-406f-8712-a9ce806a748d@googlegroups.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-03-26 15:19 -0600
Subject Re: Dynamically reference variable in object
Newsgroups comp.lang.python
Message-ID <mailman.8586.1395868786.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On Mar 26, 2014 5:48 AM, "Ben Collier" <bmcollier@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Dynamically reference member of array Ben Collier <bmcollier@gmail.com> - 2014-03-26 04:43 -0700
  Dynamically reference variable in object Ben Collier <bmcollier@gmail.com> - 2014-03-26 04:44 -0700
    Re: Dynamically reference variable in object Ian Kelly <ian.g.kelly@gmail.com> - 2014-03-26 15:19 -0600
      Re: Dynamically reference variable in object Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-03-26 23:42 +0000
  Re: Dynamically reference member of array "R. Michael Weylandt" <michael.weylandt@gmail.com> - 2014-03-29 22:50 -0400

csiph-web