When is the output of repr useful?

会有一股神秘感。 提交于 2019-12-21 16:59:00

问题


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:

  1. that b is an instance of class A in the __main__ namespace,
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!