上下文管理协议

with open("a.txt") as f:          #打开文件,并自动关闭文件
    pass

#上下文管理协议
class Open:
    def __init__(self,name):
        self.name = name

    def __enter__(self):
        print("执行enter")
        print(self)

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):      #当出现异常时,触发,并返回__exit__中的三个参数
        print("执行exit")
        print(exc_type)           #异常类型
        print(exc_val)            #异常值
        print(exc_tb)             #异常traceback
        return True               #retrue True 当出现异常时,直接吞没异常,并结束with语句,程序继续向下运行

with Open("a.txt") as f1:         #with时会触发__enter__,拿到的结果是self,然后将self赋值给f1
    print(f1)
    print(f1.name)
    print(ssssssssss)             #当这里出现错误是,直接触发__exit__,整个程序报错结束,但返回True时,异常会被吞没,with语句结束,程序继续向下运行

    print("11111")                #当with里的代码块执行结束后,触发__exit__

print("000000000000")

 

posted @ 2019-05-15 23:54  saber゛  Views(188)  Comments(0)    收藏  举报