-5

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.

3
  • 3
    You found setattr, you must have found getattr as well? Commented Aug 28 at 20:14
  • 4
    But if you end up doing that rather ugly kind of things, you should probably rather use a dict... Commented Aug 28 at 20:15
  • A class which has an internal dict property bag for key-values is most likely the cleanest way to implement whatever you are trying to do. Commented Aug 28 at 20:19

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.