• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > 理解Python中的With语句

理解Python中的With语句

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python with语句,python中的with语句,python with as,python startswith,python startwith等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

 有一些任务,可能事先需要设置,事后做清理工作。对于这种场景,Python的with语句提供了一种非常方便的处理方式。一个很好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。 Without the with statement, one would write something along the lines of: 如果不用with语句,代码如下:

file = open("/tmp/foo.txt")
data = file.read()
file.close()
</div>

这里有两个问题。一是可能忘记关闭文件句柄;二是文件读取数据发生异常,没有进行任何处理。下面是处理异常的加强版本:

file = open("/tmp/foo.txt")
try:
  data = file.read()
finally:
  file.close()
</div>

虽然这段代码运行良好,但是太冗长了。这时候就是with一展身手的时候了。除了有更优雅的语法,with还可以很好的处理上下文环境产生的异常。下面是with版本的代码:

with open("/tmp/foo.txt") as file:
  data = file.read()
</div>

with如何工作?
 这看起来充满魔法,但不仅仅是魔法,Python对with的处理还很聪明。基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。

紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。 This can be demonstrated with the following example: 下面例子可以具体说明with如何工作:

#!/usr/bin/env python
# with_example01.py
 
 
class Sample:
  def __enter__(self):
    print "In __enter__()"
    return "Foo"
 
  def __exit__(self, type, value, trace):
    print "In __exit__()"
 
 
def get_sample():
  return Sample()
 
 
with get_sample() as sample:
  print "sample:", sample
</div>

运行代码,输出如下

bash-3.2$ ./with_example01.py
In __enter__()
sample: Foo
In __exit__()
</div>

正如你看到的, 1. __enter__()方法被执行 2. __enter__()方法返回的值 - 这个例子中是"Foo",赋值给变量'sample' 3. 执行代码块,打印变量"sample"的值为 "Foo" 4. __exit__()方法被调用 with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。 这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。

#!/usr/bin/env python
# with_example02.py
 
 
class Sample:
  def __enter__(self):
    return self
 
  def __exit__(self, type, value, trace):
    print "type:", type
    print "value:", value
    print "trace:", trace
 
  def do_something(self):
    bar = 1/0
    return bar + 10
 
with Sample() as sample:
  sample.do_something()
</div>

这没有任何关系,只要紧跟with后面的语句所返回的对象有__enter__()和__exit__()方法即可。此例中,Sample()的__enter__()方法返回新创建的Sample对象,并赋值给变量sample。 When executed: 代码执行后:

bash-3.2$ ./with_example02.py
type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
 File "./with_example02.py", line 19, in <module>
  sample.do_something()
 File "./with_example02.py", line 15, in do_something
  bar = 1/0
ZeroDivisionError: integer division or modulo by zero
</div>

 实际上,在with后面的代码块抛出任何异常时,__exit__()方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给__exit__()方法,因此抛出的ZeroDivisionError异常被打印出来了。

开发库时,清理资源,关闭文件等等操作,都可以放在__exit__方法当中。

因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。

以上就是关于Python中的With语句的理解,希望对大家的学习有所帮助。

</div>

您可能想查找下面的文章:

  • 理解Python中的With语句
  • Python 的 with 语句详解
  • python 控制语句
  • python 控制语句

相关文章

  • PYTHON压平嵌套列表的简单实现
  • python实现问号表达式(?)的方法
  • python制作一个桌面便签软件
  • Python使用PyGreSQL操作PostgreSQL数据库教程
  • python处理图片之PIL模块简单使用方法
  • Python获取当前路径实现代码
  • Python实时获取cmd的输出
  • 在Python的while循环中使用else以及循环嵌套的用法
  • Pyhton中防止SQL注入的方法
  • 让python 3支持mysqldb的解决方法

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python守护进程用法实例分析
    • Python操作MySQL数据库9个实用实例
    • Python抓取京东图书评论数据
    • Python实现文件复制删除
    • 简单的抓取淘宝图片的Python爬虫
    • Python中分数的相关使用教程
    • django 文件上传功能的相关实例代码(简单易懂)
    • python3中set(集合)的语法总结分享
    • Python编程中用close()方法关闭文件的教程
    • python抓取网页图片并放到指定文件夹

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有