__repr__定义一个类的特定返回形式

官方文档:
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.
和str一样也是返回一个字符串,repr返回的是一个可打印的字符串表示形式。在一个类中,你可以通过定义repr 来返回控制他的返回类型

#repr和str
x='avbc'
print(x)          #没有引号
print(str(x))       #没有引号
print(repr(x))  #输出的值是带引号 给python看的

定义_repr_函数

###没有定义__repr__函数的情况
class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
p = point(10, 10)
print(p)

输出的是下面这串东西,但是我们想让他输出 point(10,10)

<__main__.point object at 0x00000221EDAEE160>
#有__repr__的情况下
class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return 'point({},{})'.format(self.x, self.y)


p = point(10, 10)
print(p)

输出:

point(10,10)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值