Python的with...as...语句
来源:互联网 发布:igraph python 编辑:程序博客网 时间:2024/05/22 04:45
Python的with...as的用法
__enter__()
<class 'int'>
sample: 1111111111
这个语法是用来代替传统的try...finally语法的。
with EXPRESSION [ as VARIABLE] WITH-BLOCK基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。
紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。例子:
f = open("D://report_data2.txt")try: data = f.read()except: print("读取文件失败!")else: print(data)finally: f.close()# with...as...with open("D://report_data2.txt") as f: data = f.read()print(data)使用with...as...的方式替换,修改后的代码是:
with open("D://report_data2.txt") as f: data = f.read()print(data)
进一步说明:
class Sample: def __enter__(self): print("__enter__()") return 1111111111 def __exit__(self, type, value, trace): print("__exit__()")# 实例化with Sample() as s: print(type(s)) print("sample:", s)执行结果为
__enter__()
<class 'int'>
sample: 1111111111
__exit__()
说明:
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是int 1111111111,赋值给s变量
3. 执行代码块,打印变量s的值为 11111111
4. __exit__()方法被调用with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数- val, type 和 trace。这些参数在异常处理中相当有用。
收藏:https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/
阅读全文
0 0
- Python 的 with ... as ... 语句
- Python的with...as...语句
- 理解Python的With as语句
- 理解Python的With as语句
- 理解Python的With as语句
- 理解Python的With as语句
- 理解python的with as 语句
- 【Python基础】with as 语句
- python中with as 语句的作用以及意义
- python中的with-as语句学习
- python的with...as...用法
- Python的with...as、convert()
- python with as的用法
- python with as的用法
- oracle和sql的with as 语句
- oracle with as语句的DDL尴尬
- oracle中with as语句的使用
- sql中With AS语句的用法
- mysql外键约束
- Maven 连接ORACLE 数据库最后还是没搞定,过程记录一下
- Ubuntu系统中安装RPM格式包
- thinkphp+uploadify上传图片,实现缩略图浏览
- angularJS控制器
- Python的with...as...语句
- ES 5.x bulk update重复的文档ID性能低下分析
- Python3.6游戏设计(小学入门级别)
- CCF 201509-3 模板生成系统
- Jquery动态增加行和删除行并封装成list表单提交
- C++操作MySQL大量数据插入效率低下的解决方法
- Mysql数据库操作(五)----约束
- centos7 mysql数据库安装和配置
- 欢迎使用CSDN-markdown编辑器