上下文管理

一 、上下文协同管理(__enter__和 __exit__)

# class Foo:
#     def __init__(self,name):
#         self.name = name
#     def __enter__(self):
#         print('执行enter',self)
#         return self
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print('执行exit')
#         print(exc_type)
#         print(exc_val)
#         print(exc_tb)
#
# with Foo('a.txt') as f:   # 相当于f = obj.__enter__() ##  with时触发enter
#     print('------')
#     print('=====')
# print('000000')    ### 上面的代码块执行完毕时触发exit
## 没有异常时,with 下的代码块运行完毕,自动触发exit,exc_type, exc_val, exc_tb三个参数均为None

# class Foo:
#     def __init__(self,name):
#         self.name = name
#     def __enter__(self):
#         print('执行enter',self)
#         return self
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         print('执行exit')
#         print(exc_type)
#         print(exc_val)
#         print(exc_tb)
#
# with Foo('a.txt') as f:   # 相当于f = obj.__enter__() ##  with时触发enter
#     print('------')
#     print(sdhf)   ## 异常
#     print('=====')
# print('000000')
## 有异常时,到异常那句代码,直接触发、__exit__,此时三个参数为
# exc_type  <class 'NameError'>;
# exc_val name 'sdhf' is not defined
###  exc_tb <traceback object at 0x0000000002203148>

class Foo:
    def __init__(self,name):
        self.name = name
    def __enter__(self):
        print('执行enter',self)
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        print('执行exit')
        print(exc_type)
        print(exc_val)
        print(exc_tb)
        return True

with Foo('a.txt') as f:   # 相当于f = obj.__enter__() ##  with时触发enter
    print('------')
    print(sdhf)   ## 异常
    print('=====')
print('000000')
## 有异常,但是exit返回值为True时,会吞掉异常,遇到异常那句代码,执行exit,然后开始执行with外面的代码

# 好处
#1.使用with语句的目的就是把代码放在with中执行,with结束后,自动完成清理工作,无需手动干预
#2.在需要管理一些资源,比如文件,网络连接,和锁的编程环境中,可以在__exit__中定制自动释放资源的机制。

猜你喜欢

转载自www.cnblogs.com/benson321/p/9551052.html