Continue with the previous example: http://blog.51cto.com/lavenliu/2126344
Look at the example of the plural in the front, add the __str__
attribute here,
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__要返回一个字符串。
Two visualization methods, __str__
and __repr__
methods. Their differences and connections are:
- Same point
- Both require a string to be returned
- Different points
__str__
The returned string is closer to the natural language;
__repr__
The returned string is more reflective of the interpreter-related;
- The above is just an agreement;
Object-oriented object visualization of Python