の原則とのpython

オブジェクトの要件を最初の使用は、コンテキスト管理プロトコル(コンテキスト管理プロトコル)をサポートし、それは単に内部クラスは__enter__と__exit__メソッドを実装しています。

内蔵のこれらの2つの方法のオブジェクト:

  • ファイル
  • decimal.Context
  • thread.LockType
  • threading.Lock
  • threading.RLock
  • threading.Condition
  • threading.Semaphore
  • threading.BoundedSemaphore

この2つのクラスのメソッドのカスタム実装:

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

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

使用します。

with MyTest() as mytest:
    pass

結果:

より一般的なファイル:

Fとしてオープン(パス、 '+ W')を有します。

    パス

我々は、すべてのioは閉じる必要があり、最後の操作は、ファイルが構築されたクローズコード__exit__方法で使用することは明らかであることを知っています。

おすすめ

転載: blog.csdn.net/ryuhfxz/article/details/85600099