標籤: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__
方法。它們的區別與聯絡是:
- 相同點
- 不同點
__str__
返回的字串更接近自然語言;
__repr__
返回的字串更多的反映解譯器相關的;
- 以上只是個約定而已;
Python物件導向之-對象可視化