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

Python中的with...as用法介绍

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

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

这个语法是用来代替传统的try...finally语法的。
with EXPRESSION [ as VARIABLE] WITH-BLOCK
</div>
基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。

紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。
file = open("/tmp/foo.txt")
try:
    data = file.read()
finally:
    file.close()
</div>
使用with...as...的方式替换,修改后的代码是:
with open("/tmp/foo.txt") as file:
    data = file.read()
#!/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>
执行结果为
In __enter__()
sample: Foo
In __exit__()
</div>

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

</div>

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

  • Python中的with...as用法介绍
  • Python中的with...as用法介绍
  • python中as用法实例分析
  • python中as用法实例分析

相关文章

  • python 获取文件列表(或是目录例表)
  • Python连接数据库学习之DB-API详解
  • Python 类与元类的深度挖掘 I【经验】
  • Python中使用第三方库xlrd来读取Excel示例
  • 在IIS服务器上以CGI方式运行Python脚本的教程
  • python定时检查某个进程是否已经关闭的方法
  • python使用正则表达式检测密码强度源码分享
  • Python 初始化多维数组代码
  • Python获取Windows或Linux主机名称通用函数分享
  • python操作字典类型的常用方法(推荐)

文章分类

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

最近更新的内容

    • 基于Python 的进程管理工具supervisor使用指南
    • Python遍历文件夹和读写文件的实现代码
    • Python操作Access数据库基本步骤分析
    • 教你用python3根据关键词爬取百度百科的内容
    • Python使用scrapy采集时伪装成HTTP/1.1的方法
    • python2.7删除文件夹和删除文件代码实例
    • 浅述python中argsort()函数的实例用法
    • Python中super的用法实例
    • Python中查看文件名和文件路径
    • Python采用Django开发自己的博客系统

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

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