One of the Rubik's Cube methods--class construction (__init__, __new__) and destructor (__del__) methods

  1. Construction method (see the small turtle introductory tutorial)

    __init__() method: the initialization method of the class, called when the class object is initialized, and then called when needed

  Note: The return value of this method must be None

 class Rectangle():
       def __init__(self,width,height):
           self.width =width
           self.height=height  
View Code

 

 __new__() method: The actual call is called before __init__(). The first method to be called when an object is instantiated. Called when an object is newly created, it is generally not overridden, inherited from immutable type to show its function

   class CapStr(str):
       def __new__(cls,string):
           string=str.upper(string)
           return str.__new__(cls,string)
   a=CapStr('I will be transfer')
   print(a) #结果 I WILL BE TRANSFER
View Code
  1. Destructor

  The __del__() method is called when the garbage collection mechanism reclaims the object . This method is not necessarily called when the object is deleted . This method is called only when the content in the object address is deleted.

  

def  __del__ (self):
     print ( ' __del__ method was called ' )        
b,c=a,a
c = a
 print ( ' del a ' )
 del a
 print ( ' del b ' )
 del b
 print ( ' del c ' )
 del c # __del__ method is called
View Code

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324771390&siteId=291194637