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__