Difference between __str__ and __repr__?

I am writing this code:

class Item: def __init__(self, name): self._name = name; def __str__(self): return "Item: %s" % self._name 

When i started

 print((Item("Car"),)) 

output

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

then prints

 (Item: Car,) 

So now I am confused by the difference between __repr__ and __str__ .

+7
python
source share
1 answer

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

+16
source share

All Articles