程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Python >> Python內置函數(53)——repr

Python內置函數(53)——repr

編輯:Python

英文文檔:

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.

 

說明:
  1. 函數功能返回一個對象的字符串表現形式。其功能和str函數比較類似,但是兩者也有差異:函數str() 用於將值轉化為適於人閱讀的形式,而repr() 轉化為供解釋器讀取的形式。
>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"

  2. repr函數的結果一般能通過eval()求值的方法獲取到原對象。

>>> eval(repr(a))
'some text'

  3. 對於一般的類型,對其實例調用repr函數返回的是其所屬的類型和被定義的模塊,以及內存地址組成的字符串。

>>> class Student:
    def __init__(self,name):
        self.name = name

>>> a = Student('Bob')
>>> repr(a)
'<__main__.Student object at 0x037C4EB0>'

  4. 如果要改變類型的repr函數顯示信息,需要在類型中定義__repr__函數進行控制。

>>> class Student:
    def __init__(self,name):
        self.name = name
    def __repr__(self):
        return ('a student named ' + self.name)

>>> b = Student('Kim')
>>> repr(b)
'a student named Kim'
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved