深入浅析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学习笔记之os模块使用总结
Nov 03 Python
python多线程用法实例详解
Jan 15 Python
python开发之文件操作用法实例
Nov 13 Python
Python爬虫之模拟知乎登录的方法教程
May 25 Python
TensorFlow saver指定变量的存取
Mar 10 Python
Python制作动态字符图的实例
Jan 27 Python
Python3 itchat实现微信定时发送群消息的实例代码
Jul 12 Python
Django文件存储 自己定制存储系统解析
Aug 02 Python
django项目登录中使用图片验证码的实现方法
Aug 15 Python
python+Selenium自动化测试——输入,点击操作
Mar 06 Python
如何利用Python matplotlib绘制雷达图
Dec 21 Python
Python帮你解决手机qq微信内存占用太多问题
Feb 15 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使用GIFEncoder类生成的GIF动态图片验证码
2014/07/01 PHP
UPUPW 更新 64 位 Apache 系列 PHP 7.0 正式版
2015/12/08 PHP
PHP XML和数组互相转换详解
2016/10/26 PHP
解决php extension 加载顺序问题
2019/08/16 PHP
javaScript checkbox 全选/反选及批量删除
2010/04/28 Javascript
js判断字符是否是汉字的两种方法小结
2014/01/03 Javascript
html文本框提示效果的示例代码
2014/06/28 Javascript
JS获取客户端IP地址、MAC和主机名的7个方法汇总
2014/07/21 Javascript
javascript格式化指定日期对象的方法
2015/04/21 Javascript
JavaScript实现的多种鼠标拖放效果
2015/11/03 Javascript
JS实现的在线调色板实例(附demo源码下载)
2016/03/01 Javascript
JavaScript基本语法_动力节点Java学院整理
2017/06/26 Javascript
基于jQuery对象和DOM对象和字符串之间的转化实例
2017/08/08 jQuery
vue 系列——vue2-webpack2框架搭建踩坑之路
2017/12/22 Javascript
JavaScript中发出HTTP请求最常用的方法
2018/07/12 Javascript
Vue中 v-if/v-show/插值表达式导致闪现的原因及解决办法
2018/10/12 Javascript
搭建vscode+vue环境的详细教程
2020/08/31 Javascript
python开发之IDEL(Python GUI)的使用方法图文详解
2015/11/12 Python
解决Mac安装scrapy失败的问题
2018/06/13 Python
python中copy()与deepcopy()的区别小结
2018/08/03 Python
获取django框架orm query执行的sql语句实现方法分析
2019/06/20 Python
Python通过cv2读取多个USB摄像头
2019/08/28 Python
利用python3 的pygame模块实现塔防游戏
2019/12/30 Python
Python requests及aiohttp速度对比代码实例
2020/07/16 Python
Python爬虫+tkinter界面实现历史天气查询的思路详解
2021/02/22 Python
详解HTML5中rel属性的prefetch预加载功能使用
2016/05/06 HTML / CSS
我们是伦敦女孩:WalG
2018/01/08 全球购物
Glamest意大利:女性在线奢侈品零售店
2019/04/28 全球购物
铭宣海淘转运:美国、日本、英国转运等全球转运公司
2019/09/10 全球购物
.NET笔试题(20个问题)
2016/02/02 面试题
资料员的岗位职责
2013/11/20 职场文书
六年级数学教学反思
2014/02/03 职场文书
创先争优宣传标语
2014/10/08 职场文书
材料员岗位职责范本
2015/04/11 职场文书
我的中国梦主题教育活动总结
2015/05/07 职场文书
JS如何使用剪贴板操作Clipboard API
2021/05/17 Javascript