问题
I have been reading about repr
in Python. I was wondering what the application of the output of repr
is. e.g.
class A:
pass
repr(A) ='<class __main__.A at 0x6f570>'
b=A()
repr(b) = '<__main__.A instance at 0x74d78>'
When would one be interested in '<class __main__.A at 0x6f570>'
or'<__main__.A instance at 0x74d78>'
?
回答1:
Sometimes you have to deal with or present a byte string such as
bob2='bob\xf0\xa4\xad\xa2'
If you print this out (in Ubuntu) you get
In [62]: print(bob2)
bob𤭢
which is not very helpful to others trying to understand your byte string. In the comments, John points out that in Windows, print(bob2)
results in something like bobð¤¢
. The problem is that Python detects the default encoding of your terminal/console and tries to decode the byte string according to that encoding. Since Ubuntu and Windows uses different default encodings (possibly utf-8
and cp1252
respectively), different results ensue.
In contrast, the repr of a string is unambiguous:
In [63]: print(repr(bob2))
'bob\xf0\xa4\xad\xa2'
When people post questions here on SO about Python strings, they are often asked to show the repr of the string so we know for sure what string they are dealing with.
In general, the repr should be an unambiguous string representation of the object. repr(obj)
calls the object obj
's __repr__
method. Since in your example the class A
does not have its own __repr__
method, repr(b)
resorts to indicating the class and memory address.
You can override the __repr__
method to give more relevant information.
In your example, '<__main__.A instance at 0x74d78>'
tells us two useful things:
- that
b
is an instance of classA
in the__main__
namespace, - and that the object resides in memory at address 0x74d78.
You might for instance, have two instances of class A
. If they have the same memory address then you'd know they are "pointing" to the same underlying object. (Note this information can also be obtained using id
).
回答2:
Theoretically, repr(obj)
should spit out a string such that it can be fed into eval
to recreate the object. In other words,
obj2 = eval(repr(obj1))
should reproduce the object.
In practice, repr
is often a "lite" version of str
. str
might print a human-readable form of the object, whereas repr
prints out information like the object's class, usually for debugging purposes. But the usefulness depends a lot on your situation and how the object in question handles repr
.
回答3:
The main purpose of repr()
is that it is used in the interactive interpreter and in the debugger to format objects in human-readable form. The example you gave is mainly useful for debugging purposes.
来源:https://stackoverflow.com/questions/4661851/when-is-the-output-of-repr-useful