python with使用的一些例子
来源:互联网 发布:企业微信管理系统源码 编辑:程序博客网 时间:2024/05/16 07:24
while this might look like magic, the way Python handles with is more clever than magic. The basic idea is that the statement after with has to evaluate an object that responds to an __enter__() as well as an __exit__() function.
After the statement that follows with is evaluated, the __enter__() function on the resulting object is called. The value returned by this function is assigned to the variable following as. After every statement in the block is evaluated, the __exit__() function is called.
例子如下:
class RedirectionStdoutTo:def __init__(self, fd):self.out_new = fddef __enter__(self):self.old_out = sys.stdoutsys.stdout = self.out_newdef __exit__(self):sys.stdout = self.old_out
with open('Logfile') as fd:with RedirectionStdoutTo(fd):do_something()
这里open函数返回的file object对象实现了__enter__和__exit__方法,RedirectionStdoutTo()实例也实现了__enter__和__exit__方法;第一个with返回了file object对象供后续使用,第二个未明确在as后引用
这里自行写了一个小类实现tcp连接的关闭:
import socketclass mysocket: def __init__(self, sockfd): self.sockfd = sockfd def __enter__(self): print "Enter" def __exit__(self, para1, para2, para3): print "Exit" self.sockfd.close() sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sockfd.connect(("www.taobao.com", 80))with mysocket(sockfd): pass
0 0
- python with使用的一些例子
- 一些函数使用的例子
- interval使用的一些例子
- webdriver 使用的一些例子
- Sql 中 with 的使用例子
- postgreSQL 使用With字句的例子
- python字符串操作的一些例子
- python中httplib的一些例子
- Python正则表达式的一些例子
- python mock 的一些小例子
- python 中with的使用
- Python:with语句的使用
- Python HTMLParser的使用例子
- python使用sqlite3的例子
- Linux tar 的一些使用例子
- 关于apply属性使用的一些例子
- SQL*LOAD经常使用的一些例子
- raphael一些基本例子的使用
- 时尚新锋第156期半永久化妆培训班开课
- 欢迎使用CSDN-markdown编辑器
- 大自然·柯拉尼助您问鼎财富巅峰
- DM816x算法详解--之OSD
- 日语学习之沪江N3基础 20150625 -6
- python with使用的一些例子
- 要抓住机遇3
- 后台前台传入编码处理filter(最完善版本)(根据不同请求post/get不同处理)
- SQL语句简介
- LeetCode204:Count Primes
- 讲解及制作ppt的几个要点总结
- 二叉搜索的算法
- 锚点平滑跳转
- Java中字符串的一些基本操作