Class Test (object): def __init__ (self, name): self.name = name print (' This is the constructor ') def Say_hi (self): print (' Hell,%s '% self.name) def __del__ (self): print (' This is destructor ') obj = Test (' Bigberg ') Obj.say_hi () del obj #输出 This is the constructor Hello Bigberg this is a destructor
constructor function
Used to initialize the contents of the class state, Python provides a constructor-style __init__ (), that is, when the class is instantiated to execute the function, the __init__ () method is optional, if not provided, Python will give the default __init__ method.
Destructors
"__del__" is a destructor, when using Del to delete an object, it will call his own destructor, in addition, when the object is called in a scope, the destructor will be called once when it jumps out of its scope, which can be used to free memory space.
__DEL__ () is optional, and if not provided, Python provides default destructors in the background
If you want to explicitly call a destructor, you can use the DEL keyword: del obj
garbage collection Mechanism
s = ' 123 ' Print (' del ... Running ') del s
When we delete an object with Del, we do not actually clear the object's memory space directly. Python uses the ' reference count ' algorithm to handle recycling, which means that when an object is no longer referenced by another object within its scope, Python automatically clears the object.
The destructor __del__ () automatically clears the memory space of the deleted object when it is referenced.
constructor function:
Used to initialize the contents of the class state, Python provides a constructor-style __init__ ();
That is, the function is executed when the class is instantiated. Then we can put the attributes that we want to initialize first into this function. The following programs:
The __init__ () method is optional and if not provided, Python gives the default __init__ method
Get and set methods for general data acquisition need to be defined