Python Advanced (15) – Special Methods of Class Objects (2)

Original link: https://chegva.com/5304.html

◎Knowledge points

  1. Special methods of class objects __str__() and __repr__()

  2. The special method of class object __new__()

◎Script practice

Special methods of class objects __str__() and __repr__()

 """One, special methods of class objects __str__() and __repr__()"""  """ The special methods __str__() and __repr__() of class objects are used to customize and return the string representation of the instance object 1. When printing an instance object directly on the interactive command line, If the special method __repr__() is implemented in the class object corresponding to the instance, this method will be called automatically; Otherwise, the class object corresponding to the instance object and the address of the instance object in memory will be printed  2. When calling the built-in function print to print an instance object, If the special method __str__() is implemented in the class object corresponding to the instance object, this method will be called automatically; otherwise, if the special method __repr__() is implemented in the class object corresponding to the instance object, this method will be called automatically; Otherwise, the class object corresponding to the instance object and the address of the instance object in memory will be printed. 3. When the built-in function str is called to create a string and the actual parameter is an instance object, If the special method __str__() is implemented in the class object corresponding to the instance object, the method will be automatically called inside the built-in function str; Otherwise, if the special method __repr__() is implemented in the class object corresponding to the instance object, the method will be automatically called inside the built-in function str; Otherwise, the class object corresponding to the instance object and the address of the instance object in memory will be printed  4. When the built-in function repr is called to create a string and the argument is an instance object, If the special method __repr__() is implemented in the class object corresponding to the instance object, the method will be automatically called inside the built-in function repr; Otherwise, the class object corresponding to the instance object and the address of the instance object in memory """ will be printed  """ >>> class MyClass(object): ... pass ...  >>> mc = MyClass() >>> mc <__main__.MyClass object at 0x103f41550> >>> print(mc) <__main__.MyClass object at 0x103f41550> >>> str(mc) '<__main__.MyClass object at 0x103f41550>' >>> repr(mc) '<__main__.MyClass object at 0x103f41550>' """  """ >>> class MyClass(object): ... def __str__(self): ... return "__str__ was called" ...  >>> mc = MyClass() >>> mc <__main__.MyClass object at 0x103e5c588> >>> print(mc) __str__ is called >>> str(mc) '__str__ was called' >>> repr(mc) '<__main__.MyClass object at 0x103e5c588>' """  """ >>> class MyClass(object): ... def __repr__(self): ... return "__repr__ was called" ...  >>> mc = MyClass() >>> mc __repr__ is called >>> print(mc) __repr__ is called >>> str(mc) '__repr__ was called' >>> repr(mc) '__repr__ was called' """  """ >>> class MyClass(object): ... def __str__(self): ... return "__str__ was called" ... def __repr__(self): ... return "__repr__ was called" ...  >>> mc = MyClass() >>> mc __repr__ is called >>> print(mc) __str__ is called >>> str(mc) '__str__ was called' >>> repr(mc) '__repr__ was called' """  """ In general, the implementation code of the special methods __str__() and __repr__() of class objects is the same, therefore, When one of them is implemented, its method name can be assigned to the other's method name """  class MyClass(object): def __str__(self): return "xxx"  __repr__ = __str__  """ The built-in functions str() and repr() both return a string representation of an object, with the difference: The return value of str() is for users to see, which is more user-friendly The return value of repr() is for program developers to see, for debugging services >>> str("Hello,\nWorld!") 'Hello,\nWorld!' >>> repr("Hello,\nWorld!") "'Hello,\\nWorld!'" """ 


The special method of class object __new__()

 """Second, the special method of class object __new__()"""  """ When creating an instance object with "class name ([actual parameter])", the main processing process of the python interpreter consists of two major steps: 1. Call the special method __new__() to create an instance object. First, it will check whether the object of this class implements the special method __new__(). If it does not, it will search in its parent class in turn. until the class object object The special method __new__() will return the created instance object. 2. Call the special method __init__() to initialize the created instance object. The instance object returned by __new__() will be automatically passed as an argument to the first step of __init__(). a parameter self """  class Parent(object): def __new__(cls, *args, **kwargs): # The __new__() of the parent class is called, and its formal parameter cls corresponds to the id of the actual parameter: 140398668516112 print("__new__() of the parent class is called, and its formal parameter cls corresponds to the id of the actual parameter: %s" % id(cls)) obj = super().__new__(cls) # object's special method __new__() knows how to create instance objects print("id of created instance object: %s" % id(obj)) # created instance object's id : 4430051744 return obj  class Child(Parent): def __init__(self, name): # The __init__() of the subclass is called, and its formal parameter self corresponds to the id of the actual parameter: 4430051744 print("The __init__() of the subclass is called, and its formal parameter self corresponds to the id of the actual parameter: %s" % id(self)) self.name = name  print("id of parent class: %s" % id(Parent)) # id of parent class: 140398668515168 print("Subclass id: %s" % id(Child)) # Subclass id: 140398668516112  child = Child("Mike") print("The id of the created instance object: %s" % id(child)) # The id of the created instance object: 4430051744

类对象的特殊方法之__new__().png


◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/special_methods2.py

This article is reprinted from: https://chegva.com/5304.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment