Home > Back-end >  Iterating through list elements and apply to class
Iterating through list elements and apply to class

Time:01-28

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?

CodePudding user response:

You can get attributes using the following:

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=}')
  •  Tags:  
  • Related