Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKohei Ashida
4,882 PointsWhy is "__repr__" used here? and Why should it return with str() function?
I run code without str() function in the __repr__
intentionally and I got an TypeError: __repr__
returned non-string (type int).
I thought it looks YatzyHand() list is composed of int type indices but according to this error message, the list is composed of string type indices?
I got confused because the list of YatzyHand() looks to me that the indices of the list is int type but the __repr__
is set with str() function.
If it returns str type in the list of YaztyHand(), why doesn't the list look like string type as below?
["2","2","4","5", "5"] #A list of str type indices
[2, 2, 4, 5, 5] #this is the list of YatzyHand() in the lesson
3 Answers
Steven Parker
231,275 PointsThe list is not composed of strings, but of D6 objects. The "repr" function returns a string that can be used to represent the object for printing. But it doesn't convert the object itself into a string.
If you defined the "repr" function as return "cat"
, you'd see (also with no quotes):
[cat, cat, cat, cat, cat]
If you're wondering why the function was used at all, try removing it completely and see what the output looks like.
Kohei Ashida
4,882 PointsThank you! Now I understand what's happening with this function by removing it and checking the output.
Roger Perell贸
4,293 PointsI'm a bit late to this conversation, buy does anyone know why str doesn't work in this case instead of repr?