Python 内建函数 - repr(object)

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。

拓展阅读

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值