python的repr和str有什么不同_str()和repr()的异同
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 --
總結
以上是生活随笔為你收集整理的python的repr和str有什么不同_str()和repr()的异同的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql内置变量_MySQL常用内置变
- 下一篇: splunk中 如何隐藏input_翻糖