日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python的repr和str有什么不同_str()和repr()的异同

發布時間:2025/3/11 python 53 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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()的异同的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。