美文网首页python自学我爱编程
python 实现上下文管理功能

python 实现上下文管理功能

作者: 洛克黄瓜 | 来源:发表于2018-05-28 16:09 被阅读15次

上下文是什么?

  • 带有with的代码块
  • 上下文的好处是可以避免资源忘了释放
  • 理论派可以去看看网上资料
  • 下面的例子很直观
# -*- coding: utf-8 -*-
"""什么是上下文,看下下面的例子先"""

f = open('hello.txt', 'w')
try:
    f.write('hello, world')
finally:
    f.close()

with open('hello.txt', 'w') as f:
    f.write('hello, world!')

通过类做一个上下文,来处理文件编辑

  • 有一个实例方法__enter__(self),用来返回上下文对象(上面例子里的f)
  • 有一个实例方法__exit__(self, exc_type, exc_val, exc_tb),用来关闭资源
  • __exit__方法的参数exc_type, exc_val, exc_tb是发生异常时传入的异常类型、异常值、异常的trace_back。
# -*- coding: utf-8 -*-
"""自己实现一个处理文本的上下文处理器, 我们用来写个文件"""

class ManageFile(object):

    def __init__(self, file_name, handle):
        self.file_name = file_name
        self.handle = handle
    
    def __enter__(self):
        self.file = open(self.file_name, self.handle)
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

with ManageFile('hello.txt', 'w') as f:
    f.write('haha')

通过contextlib库来做一个上下文,来处理文件编辑

# -*- coding: utf-8 -*-
"""通过contextlib实现一个上下文处理器"""

from contextlib import contextmanager

@contextmanager
def manage_file(file_name, handle):
    try:
        f = open(file_name, handle)
        yield f
    finally:
        f.close()

with manage_file('hello2.txt', 'w') as f:
    f.write('hello2')

福利:用上下文来实现排版打印

# -*- coding: utf-8 -*-
"""利用上下文实现间隔打印"""

class Indenter(object):
    def __init__(self):
        self.level = 0

    def __enter__(self):
        self.level += 1
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.level -= 1

    def print_(self, text):
        print '    ' * self.level + text

with Indenter() as indent:
    indent.print_('hi!')
    with indent:
        indent.print_('locke')
        with indent:
            indent.print_('cucumnber')
    indent.print_('over')

相关文章

  • python 实现上下文管理功能

    上下文是什么? 带有with的代码块 上下文的好处是可以避免资源忘了释放 理论派可以去看看网上资料 下面的例子很直...

  • 6-contextlib

    contextlib 在python 中只要正确实现了上下文管理管理,就可以使用 with 语句。而 contex...

  • python上下文管理

    什么是上下文管理 上下文:context的直译, 指的是代码执行过程中的前后状态上下文管理器:python上下文管...

  • Python上下文管理器和with块

    python中with语句用起来很方便,那这后边的原理就是python中的上下文管理器。 1.什么是上下文管理器 ...

  • 算法面试 - 问题记录

    python上下文管理器,装饰器? (1)上下文管理器知乎链接:https://zhuanlan.zhihu.co...

  • Python上下文管理器

    上下文管理器 概念:实现了上下文协议的对象即为上下文管理器。 上下文管理器的协议: __enter__进入的方法_...

  • python 让对象支持上下文管理协议

    8.3 通过with语句出发,让对象支持上下文管理协议 需要实现 enter 、exit 方法 这个类的核心功能就...

  • python 让对象支持上下文管理协议

    8.3 通过with语句出发,让对象支持上下文管理协议 需要实现 enter 、exit 方法 这个类的核心功能就...

  • python 基础深入

    contextlib 上下文管理器 创建上下文管理实际就是创建一个类,添加enter和exit方法 Python...

  • contextlib

    任何对象,只要正确实现了上下文管理,就可以用于with语句。实现上下文管理是通过__enter__和__exit_...

网友评论

    本文标题:python 实现上下文管理功能

    本文链接:https://www.haomeiwen.com/subject/wusgjftx.html