str()函数和repr()函数,都是Python内置的标准函数。这两个函数都是根据参数对象返回一个字符串,但是又有一些不一样的地方。我们在使用的时候,常常搞混,倾向于使用简单明了的str()函数,而搞不清楚为什么还有一个不知所云的repr()函数。本文对此进行介绍。
str()和repr()的相同之处
str()和repr(),都是返回一个字符串出来,这个字符串,来自它们的参数。
以上的代码显示,前面都是相同的,都是返回相同的字符串。唯一不同的地方在最后4行,repr 函数返回的字符串,外面多了一对双引号(",后面解释原因)。
str()和repr()的差异
先来看有差异的一段示例代码:
>>> import datetime
>>> today = datetime.date.today()
>>> str(today)
'2019-08-09'
>>> repr(today)
'datetime.date(2019, 8, 9)'
对照上面有差异的示例代码,说明str()函数跟repr()函数的不同之处:
str()函数致力于为终端用户创造字符串输出,而repr()函数的返回字符串主要是用于软件开发的debugging和developement;
str()函数的返回字符串的目标的是可读性(readable),而repr()函数的返回的目标是准确和无歧义;
repr()函数返回的字符串是正式地(offcially)代表某个对象,而str()返回的字符串是非正式地;
str()函数调用的是对象的__str__()函数,repr()函数调用的是对象的__repr__()函数。
在Python官方文档中,对repr()函数是这样解释的:
repr(object)
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
这段英文解释了一个细节,有一些对象(主要是Python内置的几个,还不是所有的)的repr()函数返回值,可以直接给eval()函数用于创建此对象,这就是前面示例代码,repr函数的返回中,多了一对双引号的原因。上面的那个代码示例,我们继续多写几行来测试:
>>> today = eval(repr(today))
>>> today
datetime.date(2019, 8, 9)
这段解释还说,对于很多Python内置的对象而言,如果不能满足eval函数,repr函数就会返回一个字符串,前面是用三角括号围起来的对象类型信息,后面是一些额外的信息,通常包含对象的名称和地址等。因此,我们在try...except...结构中获取异常信息的时候,通常都是使用repr函数,而不是str函数。
对自定义类型使用str()和repr()函数
前面解释过了,str()函数调用的是对象的__str__()函数,repr()函数调用的是对象的__repr__()函数。所以,只要自定义类型有这两个函数的定义,就可以使用Python标准库中的这两个函数。
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f'I am {self.name}'
def __repr__(self):
return f'{self.name}'
>>> from test import Person
>>> p1 = Person('xinlin')
>>> str(p1)
'I am xinlin'
>>> repr(p1)
'xinlin'
上面这段示例代码,先定义一个Person类,然后创建p1对象,再用str和repr函数去测试p1对象的返回值。
以上就是对str()函数和repr()函数异同的介绍!
-- EOF --