1. 程式人生 > >Python面向對象之-對象可視化

Python面向對象之-對象可視化

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.real
c1.imag
c1 # 這裏的輸出也可以定制,增加__repr__方法

‘{}‘.format(c1)
str(c) # str調用對象的__str__方法。__str__要返回一個字符串。

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

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

Python面向對象之-對象可視化