上下文管理器

和装饰器类似,都是包装其他代码的工具。

装饰器主要用于包装代码块(函数或类(类方法)),而上下文管理器可以包装任何格式的代码块。

1个关键字 with 

2个方法:enter,exit

使用情景1:

with open(the_file) as f:

    f.read()

使用情景2:

class contextManager:

        def __enter__(self):

                pass

        def __exit__(self):

                pass

condition1:

class contextManger2:
    def __exit__(self,exc_type,exc_instance,traceback):
        if not exc_type:
            return True
        elif exc_type == ValueError:
            print("handing valueerror:%s" %exc_instance)
            return True
        else:
            return False

with contextManger2 as c2:
    raise ValueError("this is a error")

Traceback (most recent call last):
  File "D:\userdata\xiguan\workspace\practice\context.py", line 28, in <module>
    with contextManger2 as c2:
AttributeError: __exit__

猜你喜欢

转载自my.oschina.net/u/3055388/blog/1630607
今日推荐