深入浅析python with语句简介

作者:John_Lan_2008 时间:2022-06-30 20:23:16 

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语句简介网站的支持!

来源:https://blog.csdn.net/John_Lan_2008/article/details/79880781

标签:python,with,语句
0
投稿

猜你喜欢

  • 使用go求幂的几种方法小结

    2023-09-23 05:07:45
  • Python面向对象实现一个对象调用另一个对象操作示例

    2023-08-30 22:54:35
  • python判断一个变量是否已经设置的方法

    2022-06-09 19:33:15
  • python实现简单flappy bird

    2022-08-03 12:06:33
  • 浅谈Python的条件判断语句if/else语句

    2021-03-06 12:11:02
  • Web UI 设计(网页设计)命名规范

    2009-05-13 13:06:00
  • python实现层次聚类的方法

    2023-05-03 22:26:13
  • rs.open sql,conn,1,1全接触

    2007-11-01 22:46:00
  • Python解析命令行读取参数--argparse模块使用方法

    2023-06-28 22:48:45
  • python 列表降维的实例讲解

    2023-08-28 16:44:54
  • Mootools 1.2教程(9)——输入过滤第二部分(字符串)

    2008-12-01 12:25:00
  • Pandas实现聚合运算agg()的示例代码

    2023-09-27 12:35:49
  • 使用PHP Socket 编程模拟Http post和get请求

    2023-11-15 10:58:52
  • 静态网页加密工具

    2009-01-05 12:05:00
  • Python3如何在Windows和Linux上打包

    2021-04-24 13:50:50
  • 基于python实现删除指定文件类型

    2022-02-16 06:19:48
  • 响应浏览器地址栏#(hash/fragment)变化

    2009-12-28 10:45:00
  • python用tkinter开发的扫雷游戏

    2022-05-16 18:39:40
  • Python-OpenCV实现图像缺陷检测的实例

    2023-02-16 19:38:46
  • Python实现LR1文法的完整实例代码

    2022-10-06 17:56:08
  • asp之家 网络编程 m.aspxhome.com