0

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?

2
  • 1
    I'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. Commented Jan 27, 2021 at 12:37
  • 1
    you object has no instance attributes Commented Jan 27, 2021 at 12:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I dont know the attribute names. but I see, I can get the list and put the value into setattr
Don't use dir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.