The difference between __str__ and __repr__?
python
Solution
`__str__` and `__repr__` are both methods for getting a string representation of an object. `__str__` is supposed to be shorter and more user-friendly, while `__repr__` is supposed to provide more detail.
Specifically, for many data types, `__repr__` returns a string that, if you pasted it back into Python, would be a valid expression whose value would be equal to the original value. For instance, `str('Hello')` returns `'Hello'`, but `repr('Hello')` returns `"'Hello'"`, with quote marks inside the string. If you printed that string out, you'd get `'Hello'`, and if you pasted that back into Python, you'd get the original string back.
Some data types, like file objects, can't be converted to strings this way. The `__repr__` methods of such objects usually return a string in angle brackets that includes the object's data type and memory address. User-defined classes also do this if you don't specifically define the `__repr__` method.
When you compute a value in the REPL, Python calls `__repr__` to convert it into a string. When you use `print`, however, Python calls `__str__`.
When you call `print((Item("Car"),))`, you're calling the `__str__` method of the `tuple` class, which is the same as its `__repr__` method. That method works by calling the `__repr__` method of each item in the tuple, joining them together with commas (plus a trailing one for a one-item tuple), and surrounding the whole thing with parentheses. I'm not sure why the `__str__` method of `tuple` doesn't call `__str__` on its contents, but it doesn't.
Problem
I write this code: ``` class Item: def __init__(self, name): self._name = name; def __str__(self): return "Item: %s" % self._name ``` When I run ``` print((Item("Car"),)) ``` the output is ``` (<__main__.Item object at 0x0000000002D32400>,) ``` When I change the code to this: ``` class Item: def __init__(self, name): self._name = name; def __repr__(self): return "Item: %s" % self._name def __str__(self): return "Item: %s" % self._name ``` it then outputs ``` (Item: Car,) ``` So now I am confused about the difference between `__repr__` and `__str__`.