国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python with用法實(shí)例

2019-11-25 17:45:11
字體:
供稿:網(wǎng)友

python中with可以明顯改進(jìn)代碼友好度,比如:

復(fù)制代碼 代碼如下:

with open('a.txt') as f: 
    print f.readlines() 

為了我們自己的類也可以使用with, 只要給這個類增加兩個函數(shù)__enter__, __exit__即可:
復(fù)制代碼 代碼如下:

>>> class A: 
    def __enter__(self): 
        print 'in enter' 
    def __exit__(self, e_t, e_v, t_b): 
        print 'in exit' 
 
>>> with A() as a: 
    print 'in with' 
 
in enter 
in with 
in exit 

另外python庫中還有一個模塊contextlib,使你不用構(gòu)造含有__enter__, __exit__的類就可以使用with:
復(fù)制代碼 代碼如下:

>>> from contextlib import contextmanager 
>>> from __future__ import with_statement 
>>> @contextmanager 
... def context(): 
...     print 'entering the zone' 
...     try: 
...         yield 
...     except Exception, e: 
...         print 'with an error %s'%e 
...         raise e 
...     else: 
...         print 'with no error' 
... 
>>> with context(): 
...     print '----in context call------' 
... 
entering the zone 
----in context call------ 
with no error 

使用的最多的就是這個contextmanager, 另外還有一個closing 用處不大
復(fù)制代碼 代碼如下:

from contextlib import closing 
import urllib 
 
with closing(urllib.urlopen('http://www.python.org')) as page: 
    for line in page: 
        print line 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 本溪| 临夏县| 台中县| 台中市| 民勤县| 烟台市| 若羌县| 五大连池市| 通许县| 紫云| 阜阳市| 宜丰县| 饶平县| 洛隆县| 桃江县| 德昌县| 古交市| 乌鲁木齐市| 锡林浩特市| 邢台县| 蒲城县| 绥宁县| 临漳县| 县级市| 盱眙县| 大英县| 贺兰县| 密云县| 池州市| 新蔡县| 桂林市| 洪湖市| 海南省| 亳州市| 台北县| 连城县| 海淀区| 罗源县| 内黄县| 合川市| 彭州市|