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__.
Following are differences: str() is used for creating output for end user while repr() is mainly used for debugging and development. repr's goal is to be unambiguous and str's is to be readable.
The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.
Python repr() Function returns a printable representation of an object in Python.
The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value as the object.
__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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With