Reputation: 452
I may have a few dozen different classes instances with varying attributes that I just need to put patterns/random values into and don't want to have to manually code it all out. Is there a way to loop thru the attributes in a class instance?
For example:
class test_class:
attr1=0
attr2=0
attr3=0
i=test_class()
#How do I do the below in a loop without knowing the attribute names?
i.attr1=1
i.attr2=1
i.attr3=1
I know how I can get a list/dict of the attributes, but how do I do it so I can assign values to those attributes? How do I programmatically loop thru the class instance attributes and assign new values?
Upvotes: 0
Views: 28
Reputation: 556
if you know the attribute names you can just use setattr
If you just want to get a list of all object's attributes you can use dir
Upvotes: 1