Dynamically reference member of array

B

Ben Collier

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
 
I

Ian Kelly

Sorry, subject was wrong. Please see below:

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.
You want to access object "attributes", not "variables". You can do this
using the functions getattr and setattr like so:
42
 
S

Steven D'Aprano

You want to access object "attributes", not "variables".

In fairness to the OP, the terminology "instance variables" meaning
attributes or members of an instance is (sadly, in my opinion) common in
some other languages, such as Java, and occasionally creeps into even the
Python docs.

I've often ranted about this, and won't repeat it now, only point out
that the preferred and most common terminology in Python circles is
"attribute", or "instance attribute" if you need to distinguish it from
"class attribute".
 
R

R. Michael Weylandt

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?

I think the pythonic term you're looking for is "attribute". See
getattr() and setattr()

Cheers,
Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,233
Members
46,820
Latest member
GilbertoA5

Latest Threads

Top