在context manager中,必须要介绍两个概念:

with as... , 和 enterexit.

下文将先介绍with语句,然后介绍 enter__和__exit, 最后介绍context manager.

  • with语句的作用

    它的好处是自动运行try finally语句,从而不需要人工去处理异常。

示例:

with open('some_file', 'w') as  opened_file:
opened_file.write('Hola!')

等同于:

file = open('some_file', 'w')
try:
file.write('Hola!')
finally:
file.close()

首先我们自己实现一个一般情况下的context manager。

class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, exc_type, exc_value, traceback):
# 三个参数是在运行过程中能引起异常的情况。 当context能够正常退出时,是哪个参数都为None.
self.file_obj.close()

当运行with语句时

with File('demo.txt', 'w') as opened_file:
opened_file.write('Hola!')

运行过程:

1、先运行 __init__ 生成文件句柄 opened_file

2. __enter__方法打开文件并且返回文件对象。

3. 将文件对象传递给句柄opened_file

4. 写文件调用.write()

5. with语句调用后__exit__,关闭这个文件。

tips:

可以补充代码在__enter____exit———— 中,这样在对文件操作的开始和退出时进行相应的动作。

另一种context manager的使用方式

使用contextlib模块。它将contextmanager当作decorator和generator使用。不需要自己构造类,写__enter____exit__函数。

示例代码:

from contextlib import contextmanager

@contextmanager
def open_file(name):
f = open(name, 'w')
yield f
f.close() with open_file('some_file') as f:
f.write('hola!')

open_file()是一个generator,

同时他作为decorator-- contextmanager的参数。

当我们运行with语句时,contextmanager会自动运行__enter____exit__.

同时写入文件是通过genarator来实现的。

Python之 context manager的更多相关文章

  1. Python——with语句、context manager类型和contextlib库

    目录 一.with语句 二.上下文管理器 三.contextlib模块 基本概念 上下文管理协议(Context Management Protocol) 包含方法 __enter__() 和 __e ...

  2. Python Study(02)之 Context Manager

    上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围.一旦对象进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存).它 ...

  3. Python上下文管理器(context manager)

    上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围.一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存).它的语 ...

  4. pythonic context manager知多少

    Context Managers 是我最喜欢的 python feature 之一,在恰当的时机使用 context manager 使代码更加简洁.清晰,更加安全,复用性更好,更加 pythonic ...

  5. Android的Context Manager(服务管理器)源码剖析-android学习之旅(99)

    Context Manager介绍 Context Manager对应的进程是servicemanager进程,它先于Service Server和服务客户端运行,进入接收IPC数据的待机状态,处理来 ...

  6. Python - Context Manager 上下文管理器

    什么是上下文管理器 官方解释... 上下文管理器是一个对象 它定义了在执行 with 语句时要建立的运行时上下文 上下文管理器处理进入和退出所需的运行时上下文以执行代码块 上下文管理器通常使用 wit ...

  7. Appium+python自动化9-SDK Manager

    前言 SDK Manager到有哪些东西是必须安装的呢? 一.SDK Manager 1.双击打开SDK Manager界面

  8. 第一个 Python 程序 - Email Manager Demo

    看了一些基础的 Python 新手教程后,深深感觉到 Python 的简洁与强大,这是我的第一个 Python Demo.下面是完整代码与执行截图. 代码: # encoding: utf-8 ''' ...

  9. 六、python中context.get()方法

    例:context.get('variant',False) 意思是如果context中不包括variant 就返回False.

随机推荐

  1. Pythonの坑

    Python closures and late binding A closure occurs when a function has access to a local variable fro ...

  2. module.exports 、 exports 和 export 、 export default 、 import

    1:commonjs规范 module.exports={a:10,b:20} var test=require('lib/test') console.log(test.a);console.log ...

  3. 51nod 1589 移数博弈 | 基数排序(ノಠ益ಠ)ノ彡┻━┻

    51nod 1589 移数博弈 题面 给出一个序列a,长度 n <= 10^7, a[i] <= 10^7 求每个长度 >= 2 的区间的最大值*次大值 之和. 题解 主要思路是求每 ...

  4. java多线程 -- ConcurrentHashMap 锁分段 机制

    hashtable效率低ConcurrentHashMap 线程安全,效率高 Java 5.0 在 java.util.concurrent 包中提供了多种并发容器类来改进同步容器 的性能. Conc ...

  5. 使用 xhprof 进行 php 的性能分析

    基于本机环境(php7,macos) 1.xhprof 扩展 php7 下安装 xhprof 扩展: git clone https://github.com/longxinH/xhprof cd x ...

  6. tp 用group去重

    $baseGoodIds_arr = [1,2,3,4,5,6,7,8,9];$relate_gimgs = D('GoodsImages')->where(['good_id' => [ ...

  7. 彻底搞懂 SQLAlchemy中的 backref

    教程源码截取: class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Colum ...

  8. 《剑指offer》面试题32----从1到n整数中1出现的次数

    题目:输入一个整数n,求从1到n这n个整数的十进制表示中1出现的次数.例如输入12,从1到12这些整数中包含1的数字有1,10,11和12,1一共出现了5次. 解法一:不考虑时间效率的解法(略) ps ...

  9. IOS艺术字及简单的图文混排

    NSString* alertText = [NSString stringWithFormat:@" 以下%d节课程(总课酬¥%.02lf)家长们尚未结课并评价,请尽快联系家长,否则无法获 ...

  10. mongo同步到es

    刚开始我找到的方案是利用 ElasticSearch 的 River 来同步数据,并在 GitHub 上到了 MongoDB River 插件:elasticsearch-river-mongodb. ...