1

I have defined an object, and I would like to be able to call attributes of that object in a loop but I am not sure how to do this. This is the (wrong) example code I wrote to try to indicate what I would like to do:

class my_data:

    def __init__(self,a,b,c,d):
        self.a = 'e'
        self.b = 'f'
        self.c = 'g'
        self.d = 'h'

test=my_data('a','b','c','d')

#print(test.a)
#e

index=['a','b','c','d']

#what I want: 
my_var = test.index[2]
#where index[2] is equivalent to c and thus my_var is 'g'

the error I get is:

AttributeError: 'my_data' object has no attribute 'index'

Which I understand, because it is looking for the specific attribute index and not the value of the array index[2], but I cannot figure out how to get around this. I need it because I want to use this in a loop.

Thanks!

  • `my_data` is a class, class is not a list. Even if it's a list it doesn't work since you use square brackets `[]` instead of parenthesis `()` for the `index` function – pxDav Oct 22 '21 at 00:16
  • You aren't storing an array at all, so index-like access won't work. The only items in your instance of `my_data` are `a`,`b`,`c`, and `d`. You access them with `test.a`, `test.b`, ... – h0r53 Oct 22 '21 at 00:16
  • Also, see [this](https://stackoverflow.com/q/5359679/14950361) for iterating. – pxDav Oct 22 '21 at 00:20

1 Answers1

0

You can get it like this:

my_var = getattr(test, index[2])
# my_var = 'g'

Each class in python also has default (but hidden) __getattribute__ and __getattr__ methods which handles getting attributes on the class. If needed you could overwrite them to define some custom behaviour, but in this case you don't need to.

QuantumMecha
  • 1,514
  • 3
  • 22
  • Thanks this is super close, but what if I the object "scans" isn't an array, but a list of special class items (I made a dummy version because the whole thing is a bit of a mess). So when I try this with the test version, it still says no attribute (Here is the code, I know it is a bit weird because it would be a lot to list the whole back code): – Katherine Cochrane Oct 26 '21 at 17:22
  • scans[1].data_to_plot=getattr(scans[1].get_channel(),'Height Sensor') – Katherine Cochrane Oct 26 '21 at 17:26
  • If this makes no sense, I totally get it. I have a sloppy work around, I was just looking for something more elegant. – Katherine Cochrane Oct 26 '21 at 17:29
  • Your code snippet is looking for an attribute named `Height Sensor` which python can't find because attributes defined with spaces in them are invalid in python. You probably meant to type `Height_Sensor`. If it still doesn't work, check that `scans[1].get_channel()` actually returns an object that has a variable or method `Height_Sensor` accessible to it. – QuantumMecha Oct 27 '21 at 00:20