Python With
2016-05-16 19:16
579 查看
with如何工作?
紧跟with后面的语句被求值后,返回对象的 __enter__() 方法被调用,这个方法的返回值将被赋值给as后面的变量。
当with后面的代码块全部被执行完之后,将调用前面返回对象的 __exit__()方法。
正如你看到的:
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’
3. 执行代码块,打印变量”sample”的值为 “Foo”
4. __exit__()方法被调用 with真正强大之处是它可以处理异常。
紧跟with后面的语句被求值后,返回对象的 __enter__() 方法被调用,这个方法的返回值将被赋值给as后面的变量。
当with后面的代码块全部被执行完之后,将调用前面返回对象的 __exit__()方法。
#!/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
bash-3.2$ ./with_example01.py In __enter__() sample: Foo In __exit__()
正如你看到的:
1. __enter__()方法被执行
2. __enter__()方法返回的值 - 这个例子中是”Foo”,赋值给变量’sample’
3. 执行代码块,打印变量”sample”的值为 “Foo”
4. __exit__()方法被调用 with真正强大之处是它可以处理异常。
相关文章推荐
- 远程访问jupyter notebook
- python遍历文件夹
- Python使用lxml模块和Requests模块抓取HTML页面的教程
- 登录知乎的爬虫
- Ubuntu 14.04下OpenCV 3.0+Python 2.7安装测试
- Python中数字类型
- 我的Python成长之路---第八天---Python基础(24)---2016年3月5日(晴)
- 我的Python成长之路---第八天---Python基础(23)---2016年3月5日(晴)
- Python之路3【第一篇】Python简介入门
- Python使用xslt提取网页数据
- Python实现协程的生产者与消费者
- 机器学习实战--k近邻算法
- python实现欧拉计划24题
- 灰帽子Python 学习记录 6
- Python-Jenkins API使用 —— 在后端代码中操控Jenkins
- windows下用Python把pdf文件转化为图片(png格式)
- [python爬虫]模拟登陆扇贝单词
- PySide——Python图形化界面入门教程(二)
- 自学Python实现简答的爬虫
- Element is not clickable at point (1108, 190). Other element would receive the click