深入浅析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高效编程技巧
Jan 07 Python
Python 探针的实现原理
Apr 23 Python
python判断字符串是否是json格式方法分享
Nov 07 Python
Python学习之用pygal画世界地图实例
Dec 07 Python
python实现员工管理系统
Jan 11 Python
python实现数据库跨服务器迁移
Apr 12 Python
python实现键盘控制鼠标移动
Nov 27 Python
Pythony运维入门之Socket网络编程详解
Apr 15 Python
Python使用dict.fromkeys()快速生成一个字典示例
Apr 24 Python
十个Python练手的实战项目,学会这些Python就基本没问题了(推荐)
Apr 26 Python
pycharm中显示CSS提示的知识点总结
Jul 29 Python
django-filter和普通查询的例子
Aug 12 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代码优化及php相关问题总结
2006/10/09 PHP
最简单的PHP程序--记数器
2006/10/09 PHP
PHP中几个常用的魔术常量
2012/02/23 PHP
php将字符串转化成date存入数据库的两种方式
2014/04/28 PHP
php实现基于微信公众平台开发SDK(demo)扩展的方法
2014/12/22 PHP
Zend Framework开发入门经典教程
2016/03/23 PHP
PHP 文件写入和读取操作实例详解【必看篇】
2019/11/04 PHP
兼容Mozilla必须知道的知识。
2007/01/09 Javascript
jquery增加时编辑jqGrid(实例代码)
2013/11/08 Javascript
JS中的log对象获取以及debug的写法介绍
2014/03/03 Javascript
js处理表格对table进行修饰
2014/05/26 Javascript
jQuery如何获取同一个类标签的所有值(默认无法获取)
2014/09/25 Javascript
JavaScript中停止执行setInterval和setTimeout事件的方法
2015/05/14 Javascript
分享jQuery插件的学习笔记
2016/01/14 Javascript
jQuery文本框得到与失去焦点动态改变样式效果
2016/09/08 Javascript
同步异步动态引入js文件的几种方法总结
2016/09/23 Javascript
Javascript中内建函数reduce的应用详解
2016/10/20 Javascript
canvas知识总结
2017/01/25 Javascript
jQuery滚动监听实现商城楼梯式导航效果
2017/03/06 Javascript
iview同时验证多个表单问题总结
2018/09/29 Javascript
JavaScript ES6常用基础知识总结
2019/02/09 Javascript
angular 服务随记小结
2019/05/06 Javascript
[05:15]2018年度CS GO社区贡献奖-完美盛典
2018/12/16 DOTA
在Django的URLconf中使用多个视图前缀的方法
2015/07/18 Python
Python装饰器基础概念与用法详解
2018/12/22 Python
Python语法分析之字符串格式化
2019/06/13 Python
详解Python二维数组与三维数组切片的方法
2019/07/18 Python
Python pip安装模块提示错误解决方案
2020/05/22 Python
爱尔兰橄榄球店:Irish Rugby Store
2019/12/05 全球购物
JYSK加拿大:购买家具、床垫、家居装饰等
2020/02/14 全球购物
产品销售计划书
2014/05/04 职场文书
专职安全员岗位职责
2015/04/11 职场文书
看上去很美观后感
2015/06/10 职场文书
导游词之包公祠
2019/11/25 职场文书
Redis集群新增、删除节点以及动态增加内存的方法
2021/09/04 Redis
漫画「你在春天醒来」第10卷封面公开
2022/03/21 日漫