Python物件導向之-對象可視化

來源:互聯網
上載者:User

標籤:Python   對象可視化   

繼續前面的例子:http://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.realc1.imagc1 # 這裡的輸出也可以定製,增加__repr__方法‘{}‘.format(c1)str(c) # str調用對象的__str__方法。__str__要返回一個字串。

兩個可視化方法,__str____repr__方法。它們的區別與聯絡是:

  1. 相同點
    • 都要求返回字串
  2. 不同點
    • __str__返回的字串更接近自然語言;
    • __repr__返回的字串更多的反映解譯器相關的;
    • 以上只是個約定而已;

Python物件導向之-對象可視化

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.