Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Dice Roller Giving a Hand

Kohei Ashida
Kohei Ashida
4,881 Points

Why 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
Steven Parker
217,590 Points

The 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 :point_right: return "cat" :point_left:, 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. :see_no_evil:

Kohei Ashida
Kohei Ashida
4,881 Points

Thank you! Now I understand what's happening with this function by removing it and checking the output.

I'm a bit late to this conversation, buy does anyone know why str doesn't work in this case instead of repr?