Python內建函數(53)——repr,python內建53repr

來源:互聯網
上載者:User

Python內建函數(53)——repr,python內建53repr

英文文檔:

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'

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.