4-12 python中的with语句/4-13 contextlib简化上下文管理器

类似于try-except-finally, with语句也是用来简化代码的。try-except和try-finally的一种特殊的配合用法是保证共享的资源的唯一分配,并在任务结束的时候释放它。比如文件(数据、日志、数据库等等)、线程资源、简单同步、数据库连接,等等。with语句的目标就是应用在这种场景中

# with比try-except-finally代码更加简化
# 上下文管理器with
# 查看魔法函数,设计两个魔法函数__enter__, __exit__

class Sample(object):
    def __enter__(self):
        #获取资源
        print('enter')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        #释放资源
        print('exit')

    def do_something(self):
        print('doing something')


with Sample() as sample:
    sample.do_something()

#运行结果:
enter
doing something
exit

下面介绍contextlib进一步简化上下文管理器

import contextlib

@contextlib.contextmanager
def file_open(file_name):
    print('file open')
    # yield之前的代码相当于__enter__操作
    yield {}
    # yield之后的代码相当于__exit__操作
    print('file end')

with file_open('bobby.txt') as f_opened:
    print('file processing')

#运行结果:
file open
file processing
file end

猜你喜欢

转载自blog.csdn.net/shfscut/article/details/80306468
今日推荐