The difference between
This question already has an answer here:
__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.
下一篇: 和...之间的不同