python in with the role

with a new syntax Python2.5 is introduced, it is a context management protocol, aimed from the process it and finally try ... except keywords and removed all the relevant code release resources, simplify try ... except .. .finally process flow

with initialization by __enter__ method, and then do the rehabilitation and treatment of abnormal __exit__

Therefore, with the use of the processing object must have The __enter __ () and The __exit __ () These two methods

The __enter wherein __ () method of the statement into the body (with statements wrapped block of code) before performing the operation, __ exit __ () method runs after the statement is finished exit the body

with statement on the occasion of access to resources, to ensure the implementation of anomalies will occur regardless of whether the course of the necessary "clean-up" operation, the release of resources, such as files automatically shut down after

Thread lock automatically acquire and release

 

The basic syntax with the statement:

  with expression[as target]:

    wuth_body

  1, parameters:

    exprssion: is an expression to be executed

    target: a variable or tuple is stored is the result of expression of the expression returns execution, optional parameters

 

Guess you like

Origin www.cnblogs.com/jcjc/p/11427984.html