深入浅析python with语句简介


Posted in Python onApril 11, 2018

with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能(2.5 版本中要通过 from __future__ import with_statement 导入后才可以使用),从 2.6 版本开始缺省可用(参考 What's new in Python 2.6? 中 with 语句相关部分介绍)。with 语句适用于对资源进行访问的场合,确保不管使用过程中是否发生异常都会执行必要的“清理”操作,释放资源,比如文件使用后自动关闭、线程中锁的自动获取和释放等。

术语

要使用 with 语句,首先要明白上下文管理器这一概念。有了上下文管理器,with 语句才能工作。

在python中读写操作资源,最后需要释放资源。可以使用try…finally结构实现资源的正确释放,python提供了一个with语句能更简便的实现释放资源。

1. python像文件的操作open等已经可以直接使用with语句

2. 可以自定义一个支持with语句对象

3. 使用contextlib也可以使用with语句对象

4. 针对需要close操作的对象with的使用

示例代码中有4种使用标注

# 自定义支持with语句的对象
class DummyRes:
  def __init__(self, tag):
    self.tag = tag
  def __enter__(self):
    print("Enter >>> {}".format(self.tag))
    return self
  def __exit__(self, exc_type, exc_value, exc_tb):
    print("Exit <<< {}".format(self.tag))
    if exc_tb is None:
      print("Exit without Exception {}".format(self.tag))
      return False
    else:
      print("Exit with Exception {}".format(self.tag))
      return True
# 支持closing 上下文with语句对象
class Closing:
  def __init__(self, thing):
    self.thing = thing
  def __enter__(self):
    return self
  def __exit__(self, exc_type, exc_value, exc_tb):
    self.thing.close()
class ClosingDemo:
  def __init__(self):
    self.acquire()
  def acquire(self):
    print("Acquire RES")
  def close(self):
    print("Close RES")
from contextlib import contextmanager
class ContextDemo:
  def __init__(self):
    print("Context Demo init")
    raise Exception
    print("Context Demo init")
  def print(self):
    print("Context Demo print 1")
    #raise Exception
    print("Context Demo print 2")
  def close(self):
    print("Context Demo close")
def context_demo():
  print("context demo in")
  raise Exception
  print("context demo out")
@contextmanager
def demo():
  print("Allocate Resoures")
  try:
    yield context_demo
  finally:
    print("raise exception")
  #yield "*** contextmanager demo ***"
  print("Free Resoures")
if __name__ == "__main__":
  # 1. 使用with语句 (自动关闭文件)
  with open("test.txt", "w") as f:
    f.write("write test")
  # 2. 自动定义with语句
  with DummyRes("test") as res:
    print("With body 1")
    raise Exception
    print("With body 2")
  # 3. 利用contextlib定义with语句
  with demo():
    print("exc demo")
  # 4. closing 上下文 (适合有close操作的情况)
  with Closing(ClosingDemo()):
    print("Use Resoures")

总结

以上所述是小编给大家介绍的python with语句简介,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
Python文档生成工具pydoc使用介绍
Jun 02 Python
Django查找网站项目根目录和对正则表达式的支持
Jul 15 Python
实例探究Python以并发方式编写高性能端口扫描器的方法
Jun 14 Python
全面了解python字符串和字典
Jul 07 Python
Python使用cx_Oracle模块操作Oracle数据库详解
May 07 Python
python多进程控制学习小结
Oct 31 Python
Python3.5内置模块之time与datetime模块用法实例分析
Apr 27 Python
Python使用pyserial进行串口通信的实例
Jul 02 Python
python装饰器相当于函数的调用方式
Dec 27 Python
在django中使用apscheduler 执行计划任务的实现方法
Feb 11 Python
Python同时迭代多个序列的方法
Jul 28 Python
python 对一幅灰度图像进行直方图均衡化
Oct 27 Python
python实现微信自动回复功能
Apr 11 #Python
Python实现检测文件MD5值的方法示例
Apr 11 #Python
python 输出上个月的月末日期实例
Apr 11 #Python
Python简单计算文件MD5值的方法示例
Apr 11 #Python
pandas 获取季度,月度,年度首尾日期的方法
Apr 11 #Python
python+pandas生成指定日期和重采样的方法
Apr 11 #Python
python dataframe astype 字段类型转换方法
Apr 11 #Python
You might like
整合了前面的PHP数据库连接类~~做成一个分页类!
2006/11/25 PHP
基于php 随机数的深入理解
2013/06/05 PHP
如何取得中文字符串中出现次数最多的子串
2013/08/08 PHP
iOS10推送通知开发教程
2016/09/19 PHP
PHP实现登录注册之BootStrap表单功能
2017/09/03 PHP
PHP fprintf()函数用法讲解
2019/02/16 PHP
一些技巧性实用js代码小结
2009/10/14 Javascript
js浮动图片的动态效果
2013/07/10 Javascript
jquery对象和DOM对象的区别介绍
2013/08/09 Javascript
javascript阻止浏览器后退事件防止误操作清空表单
2013/11/22 Javascript
JQuery的Ajax请求实现局部刷新的简单实例
2014/02/11 Javascript
超简单JS二级、多级联动的简单实例
2014/02/18 Javascript
jQuery实现的原图对比窗帘效果
2014/06/15 Javascript
更快的异步执行(setTimeout多浏览器)
2014/08/12 Javascript
jquery制作select列表双向选择示例代码
2014/09/02 Javascript
常见的jQuery选择器汇总
2014/11/24 Javascript
jquery选择器简述
2015/08/31 Javascript
node.js中的事件处理机制详解
2016/11/26 Javascript
微信小程序 navbar实例详解
2017/05/11 Javascript
JS 调试中常见的报错问题解决方法
2017/05/20 Javascript
Nodejs 和Session 原理及实战技巧小结
2017/08/25 NodeJs
django使用channels2.x实现实时通讯
2018/11/28 Javascript
使用webpack/gulp构建TypeScript项目的方法示例
2019/12/18 Javascript
python实现的一只从百度开始不断搜索的小爬虫
2013/08/13 Python
python xml.etree.ElementTree遍历xml所有节点实例详解
2016/12/04 Python
pycharm远程开发项目的实现步骤
2019/01/20 Python
python实现基于朴素贝叶斯的垃圾分类算法
2019/07/09 Python
django的分页器Paginator 从django中导入类
2019/07/25 Python
Python Websocket服务端通信的使用示例
2020/02/25 Python
python 工具 字符串转numpy浮点数组的实现
2020/03/14 Python
Python matplotlib绘制图形实例(包括点,曲线,注释和箭头)
2020/04/17 Python
Python基于gevent实现高并发代码实例
2020/05/15 Python
Servlet如何得到客户端机器的信息
2014/10/17 面试题
五一服装活动方案
2014/01/11 职场文书
党员教师四风问题对照检查材料
2014/09/26 职场文书
选对餐饮营销策略,营业额才会上涨
2019/08/27 职场文书