How does one print all the attributes of a class at once without calling for each one seperately? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does one print all the attributes of a class at once without calling for each one seperately?

25th Aug 2017, 1:56 PM
Kurylobe
6 Answers
+ 7
ClassName.__dict__ or ClassName.__dict__.keys() to be exact
25th Aug 2017, 2:05 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 7
@Edgar Thanks, good to know :)
25th Aug 2017, 3:20 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 6
Right. But @Edgar, doesn't dir() give you methods only?
25th Aug 2017, 2:46 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 1
Actually, for this task calling the built-in dir() function is more correct, instances of immutable types don't have a __dict__ attribute.
25th Aug 2017, 2:45 PM
Edgar Garrido
Edgar Garrido - avatar
+ 1
No, @Kuba, if the object doesn't supply the __dir__ method it basically returns every accessible attribute (methods included, of course).
25th Aug 2017, 2:51 PM
Edgar Garrido
Edgar Garrido - avatar
0
If you want it to be done nicely, add a __str__(self) method to your class and return the string you want to display depending of the value of each attribute. Then doing this will print this string : print(yourVariableOfClass)
25th Aug 2017, 2:47 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar