英文文檔:
repr(object)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.
>>> 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'