Object-oriented object visualization of Python

Source: Internet
Author: User

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:

    1. Same point
      • Both require a string to be returned
    2. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.