pythonloopsclassiteratoriteration

calling a class object in an iterative way on python


I made the next class

obj = MyClass()

fds=['a','b','c']

for i in fds:
  attribute_name = f"{i}"
  setattr(obj, attribute_name, [f"{i}"])
  print(obj.i)

I know that obj.i is gonna get me an error.

What I want is something similar to:

print(obj.a)
print(obj.b)
print(obj.c)

which gives me:

['a']
['b']
['c']

Is there a way to make it in an iterative way? That's why my first attempt was to make something like obj.i inside the loop.

I want to do this to check the data inside the list is what I was expecting or not. Probably instead of print is better to make a list with obj.a, obj.b and obj.c for that but I have the same problem, to append the data in an iterative way.


Solution

  • You can access an object's attributes as a dictionary with obj.__dict__

    List attributes of an object

    obj = MyClass()
    
    fds=['a','b','c']
    
    for i in fds:
      attribute_name = f"{i}"
      setattr(obj, attribute_name, [f"{i}"])
      print(obj.__dict__[attribute_name])