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>'?
Sometimes you have to deal with or present a byte string such as
If you print this out (in Ubuntu) you get
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 likebobð¤¢. 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 (possiblyutf-8andcp1252respectively), different results ensue.In contrast, the repr of a string is unambiguous:
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 objectobj‘s__repr__method. Since in your example the classAdoes 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:bis an instance of classAin the
__main__namespace,
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 usingid).