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'