It is interesting to use the lock in multipressing when using the process today, using a with lock once.
The object of the processing idea of the with in Python four with the value to be evaluated must have a __enter__ () method, a __exit__ () method.
The __enter__ () method of the returned object is called after the statement immediately following the with is evaluated, and the return value of the method returns the value to the variable following the AS.
The __exit__ () method of the previous return object is called when all the code blocks following the with are executed.
# class sample:# def __enter__ (self): # print ("in __enter ()") # return ' Foo ' # def __exit__ (self, exc_ Type, Exc_val, EXC_TB): # print (' in __exit__ () ') # # Def get_sample (): # return to sample () # with Get_sample () as sample:# Print (' Sample: ', sample)
In __enter__ () Sample:fooin __exit__ ()
The __enter__ () method is executed
__enter__ () method return value-in this case ' Foo ', assign to variable ' sample '
Execute code block, print variable ' sample ' with value ' Foo '
The __exit__ method is called
The __exit__ method with the sample class has three parameters-exc_type, Exc_val, EXC_TB,
# class sample:# def __enter__ (self): # return self# def __exit__ (self, exc_type, Exc_val, EXC_TB): # Print (' type: ', exc_type) # print (' type: ', exc_val) # print (' type: ', EXC_TB) # def do_something (self): # bar = 1/0# return bar + 10# with Sample () as sample:# sample.do_something ()
With will automatically call her class, then execute __enter__, execute the WITH method and the With method, and then execute the __EXIT__ function, which will automatically close, recycle resources and so on.
Python with AS