Built-in methods_Advanced

One: What is the built-in method?

# 定义在类内部,以__开头并以__结果的方法
# 特点:会在某种情况下自动触发执行

Two: Why use the built-in method?

In order to customize our class or object

Three: how to use the built-in method

__str__ : automatically triggered when the print target, then the return value (must be of type string) printed as a result of this output
 class People:
     DEF  the __init__ (Self, name, Age): 
        the self.name = name 
        self.age = Age 

    DEF  __str__ (Self):
         Print ( ' run ' )
         return  ' hahahah ' 


obj = People ( ' XXQ ' , 18 is )
 Print (obj)
 # run 
# hahahah 

OBJ1 = int (10 )
 Print (OBJ1)
# 10 

Print (obj. __Str__ ())
 # is running 
# hahahah 

Print (obj)   # < 'spicy cabbage students': 18> 
# running 
# hahahah 
 __del__ : trigger when clean up the object, it will first execute the method
 class People:
     def  the __init__ (Self, name, Age): 
        the self.name = name 
        self.age = Age 
        self.x = Open ( ' a.txt ' , MODE = ' W ' )
         # self.x = operating system resources occupied 

    def __del__ (Self):
         # Print ( 'RUN ...') 
        # initiating system call, tell the operating system recovery system resources associated 
        self.x.close () 

obj = People ( ' spicy cabbage students ' , 18 )
 # del obj # obj .__ del __ () 
print ( ' ============> ' )

 

Guess you like

Origin www.cnblogs.com/2722127842qq-123/p/12717513.html