深入浅析pythonwith语句简介-创新互联

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")

分享文章:深入浅析pythonwith语句简介-创新互联
URL地址:https://www.cdcxhl.com/article44/dcsjee.html

成都网站建设公司_创新互联,为您提供移动网站建设云服务器品牌网站建设网站排名自适应网站微信公众号

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网站建设