Sunday 18 June 2017

Python拾遗(一)python内建函数str()和repr()的区别

MarkdownPad Document
对于python而言,可以使用内建函数str()和repr()来将数值转化成字符串。但是,对于这两个方法,究竟有什么区别呢?
在Python tutorial中,是这么说的:
The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax).
意思是,str()这个函数用于返回相当具有可读性的数值,而repr()主要用于返回适宜解释器读取的数值,并且当该数值没有对应的字符串时,会返回一个SyntaxError
这个解释还是让人似懂非懂。什么是“具有可读性的数值”?什么又是“适合于解释器读取的数值”?
让我们先看几个例子吧。
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
在这段例子中,变量hellos保留了原来的格式,显示出了\n和引号;不过这段例子可能还是无法真正良好的表达出repr()str()函数的真正区别,让我们再看下一个例子:
>>> from datetime import datetime
>>> now = datetime.nxow()
>>> print(str(now))
2017-04-22 15:41:33.012917
>>> print(repr(now))
datetime.datetime(2017, 4, 22, 15, 41, 33, 12917)
通过str()的输出结果我们能很好知道now实例的内容,但是却丢失了now实例的数据类型信息。而通过repr()的输出结果我们不仅能获得now实例的内容,还能知道now是datetime.datetime对象的实例。
因此str()repr()的不同在于:
  • str()的输出追求可读性,输出格式要便于理解,适合用于输出内容到用户终端。
  • repr()的输出追求明确性,除了对象内容,还需要展示出对象的数据类型信息,适合开发和调试阶段使用。 另外如果想要自定义类的实例能够被str()repr()所调用,那么就需要在自定义类中重载__str____repr__方法。

No comments:

Post a Comment