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?
-
1I'm not sure what you're trying to do here... do you really want class attributes vs instance attributes here? Could you give a use case as this currently looks very anti-Pythonic.Jon Clements– Jon Clements2021年01月27日 12:37:03 +00:00Commented Jan 27, 2021 at 12:37
-
1you object has no instance attributesjuanpa.arrivillaga– juanpa.arrivillaga2021年01月27日 12:49:07 +00:00Commented Jan 27, 2021 at 12:49
1 Answer 1
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
2 Comments
dir