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

2 Answers

Steven Parker
Steven Parker
201,957 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.