Python's print and special methods __str__ and __repr__

Source: Internet
Author: User

Let me ask you a question why the print function prints parameters directly. Even the numbers? For example, print 1 prints 1. We know that the type of 1 is integer (off-topic, 1 is a constant in Python, is also an object of class int, and 1 in Java is a constant), which is supposed to be the string of the parameters that print accepts?

Reply:

Because the print function first calls the STR () function to convert the parameter to the STR type, and the STR () function calls the __str__ method in the class to which the parameter belongs, this method is defined in the object class. We know that all classes are subclasses of this object class (in Python3, even if you do not explicitly inherit the object class when you define the class, the default is the subclass of object.) But not in Python2, when defining a class in Python2 without inheriting object, it is not a subclass of object, in Pythn2 the class that does not inherit object is called the Classic class, and the class that inherits object is called the new class. While Python3 is a new class, because all classes are subclasses of object, subclasses inherit the parent class method, but we can override this __str__ method. For example:

Class M (Type):
def __init__ (self):
Pass
def __str__ (self):
Return "Gege"
Class TM (object):
Pass
__metaclass__ = M
Print (tm.__class__)
A = M ()
Print a

Python's print and special methods __str__ and __repr__

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.