python with學習

1.with在python中可以自動關閉打開的資源,使代碼更簡練。

2.with使用

def open_file(path, method):

    with open(path, method) as f:
        while True:
            content = f.readline()
            if content:
                print(content)
            else:
                break

3如果使用with必須類中實現__enter__()、__exit__()方法

class MyContext(object):
    """ test with"""

    def __init__(self, file_name, open_method):
        self.file_name = file_name
        self.open_method = open_method

    def __enter__(self):
        print("***enter***")
        self.f = open(self.file_name, self.open_method)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("***exit***")
        self.f.close()

4.python3支持裝飾器,定義上下文管理器

from contextlib import contextmanager


@contextmanager
def test_manager(path, method):
    f = open(path, method)
    yield f
    f.close()

5.with只能自動關閉資源,相當於try \finally,但是並不能處理異常,當with遇到異常時,程序仍然會崩潰,只是會在崩潰前關閉資源(調用__exit__()方法)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章