python with the principle of

First use with the requirements of the object supports the context management protocol (context management protocol), it simply is an internal class implements __enter__ and __exit__ method.

Built-in objects of these two methods:

  • file
  • decimal.Context
  • thread.LockType
  • threading.Lock
  • threading.RLock
  • threading.Condition
  • threading.Semaphore
  • threading.BoundedSemaphore

Method custom implementation of these two classes:

class MyTest:
    def __enter__(self):
        print('******enter******')

    def __exit__(self, exc_type, exc_val, exc_tb):
     print('********exit********')

use:

with MyTest() as mytest:
    pass

result:

The more common file:

with open(path,'w+') as f:

    pass

We all know that the last operation io must close, it is clear that file will use with built close code __exit__ method.

Guess you like

Origin blog.csdn.net/ryuhfxz/article/details/85600099