10

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__.

nik_m
  • 11,825
  • 4
  • 43
  • 57
BlackMamba
  • 10,054
  • 7
  • 44
  • 67

1 Answers1

18

__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.

Taymon
  • 24,950
  • 9
  • 62
  • 84
  • Beat me to it! :) http://docs.python.org/2/reference/datamodel.html#object.__repr__ – Prashant Kumar Aug 23 '13 at 02:32
  • You beat me to it as well! However, it would be useful to add a note that `__repr__` is usually expected to be a statement that would reproduce the object. From the docs: "this should look like a valid Python expression that could be used to recreate an object with the same value". – Joe Kington Aug 23 '13 at 02:34
  • ...And I realized that I completely missed the actual point of the question. Fixed. – Taymon Aug 23 '13 at 02:37
  • 1
    A small example: `from datetime import datetime as dt; dt.today().__str__(); dt.today().__repr__()` – Prashant Kumar Aug 23 '13 at 02:38