Python面向对象之-对象可视化

继续前面的例子:https://blog.51cto.com/lavenliu/2126344

看前面的复数的例子,这里增加__str__属性,

class Complex:
    def __init__(self, real, imag):
        self.real = read
        self.imag = imag

    def __add__(self, other):
        return Complex(self.real + other.real, self.imag + other.imag)

    def __sub__(self, other):
        return Complex(self.real - other.read, self.imag - other.imag)

    def __str__(self):
        if self.imag >= 0:
            return '{} + {}i'.format(self.real, self.imag)
        return '{} - {}i'.format(self.real, self.imag * -1)

    def __repr__(self):
        return '<{}.{}({}, {}) at {}>'.format(self.__module__, self.__class__.__name__, self.real, self.imag, hex(id(self)))

c1 = Complex(1, 2)
c1.real
c1.imag
c1 # 这里的输出也可以定制,增加__repr__方法

'{}'.format(c1)
str(c) # str调用对象的__str__方法。__str__要返回一个字符串。

两个可视化方法,__str____repr__方法。它们的区别与联系是:

  1. 相同点
    • 都要求返回字符串
  2. 不同点
    • __str__返回的字符串更接近自然语言;
    • __repr__返回的字符串更多的反映解释器相关的;
    • 以上只是个约定而已;

转载于:https://blog.51cto.com/lavenliu/2128173

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值