__str__ and __repr__ are both ways of getting a string representation of an object. __str__ should be shorter and more user friendly, and __repr__ should provide more details.
In particular, for many data types, __repr__ returns a string that, if you insert it back into Python, will be a valid expression whose value will be equal to the original value. For example, str('Hello') returns 'Hello' , but repr('Hello') returns "'Hello'" with quotation marks inside the string. If you printed this line, you will get 'Hello' , and if you paste it back into Python, you will get the original line.
Some data types, such as file objects, cannot be converted to strings in this way. The __repr__ methods of such objects usually return a string in angle brackets, which includes the object's data type and memory address. User-defined classes also do this unless you specifically define the __repr__ method.
When you evaluate a value in REPL, Python calls __repr__ to convert it to a string. However, when you use print , Python calls __str__ .
When you call print((Item("Car"),)) , you call the __str__ method of the tuple class, which is similar to the __repr__ method. This method works by calling the __repr__ method of each element in the tuple, combining it with commas (plus the final one for the tuple of one element) and surrounding it all with parentheses. I am not sure why the __str__ tuple method does not call __str__ in its contents, but it is not.
Taymon
source share