1. What is a built-in function: the functions defined in the class in the form of __function name__, these functions will be executed spontaneously under specific circumstances.
Second, the role of built-in functions: special objects can be customized when creating objects.
Third, the built-in function __str__: It will be automatically triggered when the object is printed, and then the return value obtained by calling this function will be printed as the content.
class Human: DEF the __init__ (Self, name, Age): the self.name = name self.age = Age obj = Human ( ' Tom ' , ' 18 is ' ) Print (obj) # class vivo undefined __str__, will by default __str__ parent class object is performed, the result is <__ __ main object Human AT 0x0000022CAE9E45E0.> class Human: DEF the __init__ : (Self, name, Age) the self.name = name self.age = Age DEF __str__ (Self): return the self.name # customized __str__, to return the object 'name' attribute value obj = Human ( ' Tom ' , ' 18 is ' ) Print (obj) # print target, i.e., printing a return __str__ Value, which is the value of the object's 'name' attribute, the result is tom
Fourth, the built-in function __del__: When clearing an object, the function is triggered before the operation of clearing the object.
class Human: DEF the __init__ (Self, name, Age): the self.name = name self.age = Age DEF the __del__ (Self): Print ( ' delete your sister ' ) obj = Human ( ' Tom ' , ' 18 is ' ) del obj Print ( ' program coming to an end ' ) # triggers __del__ function inside the class definition before deleting obj, the result is delete your sister ===> program near the end of class Human: DEF __init__(Self, name, Age): self.name = name self.age = Age DEF __del__ (Self): Print ( ' delete your sister ' ) obj = Human ( ' tom ' , ' 18 ' ) Print ( ' program coming to an end ' ) # automatically at the end of the recovery is not manually delete obj obj program memory, it will also trigger __del__ function, the result is a program coming to an end ===> delete your sister class Human: DEF __init__ (Self, name, Age ): self.name = name self.age= Age self.f = Open (r ' 00 notes .txt ' , ' rb ' ) # object created will be a file handle attribute DEF __del__ (Self): self.f.close () # Since the end of the program only Reclaim the application's memory resources, the system's memory usage will not be automatically released, so here you need to customize the __del__ function to automatically release the system memory usage at the end of the program