-1

I'm looking to establish a list, (list_=[a,b,c]), iterate over the list and apply it to a class (class_). So something like this:

for letter in list_:
     x = class_.letter

Is this possible?

martineau
  • 119,623
  • 25
  • 170
  • 301
kduf
  • 15
  • 4

1 Answers1

1

Attributes are typically accessed from a class using a dot notation, ex: my_class.attribute_1. This is useful when accessing attributes are hard coded.

But as you point out, this is not useful when needing to dynamically access attributes, as in the case of the list above. The solution in these cases is to access attributes using the getattr() method which takes input of your class and the attribute name. Ex: x = 'attribute_1, getattr(my_class, x) would return the same results as my_class.attribute_1.

It is worth pointing out that attributes can be set in a similar way: my_class.foo = 1 is equivalent to setattr(my_class, 'foo', 1).

Here is a solution where attributes are accessed using a list (from an example class):

class MyClass:
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

# Instantiate your class
my_class = MyClass()

# Create a list of letters
list_1 = ['a', 'b', 'c']

# Get attributes
for letter in list_1:
    x = getattr(my_class, letter)
    print(f'{letter=}, {x=}')
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
  • 1
    Noted. And improved answer @martineau – Yaakov Bressler Jan 28 '22 at 15:40
  • It's also possible to dynamically get a list of the attributes via the built-in [`vars()`](https://docs.python.org/3/library/functions.html#vars) function instead of hardcoding them like that. See [my answer](https://stackoverflow.com/a/70808540/355230) to [Programmatically / Dynamically concatenate parameters to an object to access data](https://stackoverflow.com/questions/70807561/programmatically-dynamically-concatenate-parameters-to-an-object-to-access-dat) for an example. – martineau Jan 28 '22 at 15:50
  • Neat! I started a thread on your answer there @martineau – Yaakov Bressler Jan 28 '22 at 16:03