Manual
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.
直译
返回一个字符串,该字符串包含一个可打印表述的对象。对于很多类型,当传入eval()时,该函数属试图返回一个字符串,该字符串可以产生具有相同值的对象。否则,该表述作为一个字符串被嵌入尖括号,括号内包括对象类型名和附加信息(包括对象名和地址)。一个类可以通过定义__repr__()
方法,来控制该函数为它的实例返回什么内容。
实例
简单使用
>>> repr('[]')
"'[]'"
>>> repr([1, 2, 3, 4])
'[1, 2, 3, 4]'
>>> repr('')
"''"
>>> repr('Hello World!')
"'Hello World!'"
>>> repr(())
'()'
>>> repr(('What we hold is what we will!'))
"'What we hold is what we will!'"
>>> repr(1 + 2)
'3'
槽点1
>>> x = 1 + 2
>>> repr(x)
'3'
>>> eval(repr(x))
3
# 注意比对repr()和eval()输出结果,repr()输出结果为字符串,足以见得eval()输出结果即为对象本身
槽点2
>>> def fetchSuit():
pass
>>> repr(fetchSuit)
'<function fetchSuit at 0x028C7F18>'
# 对象类型名 对象名和地址
槽点3
>>> class wanQuanGaoBuDong:
def __repr__(self):
return 'Light Me' + ' - My Sun!'
>>> gaoDing = wanQuanGaoBuDong()
# 注意此处为实例
>>> repr(gaoDing)
'Light Me - My Sun!'
Note
理解该函数的前提是,注意传入参数为object。