国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 麦盖提县| 江源县| 宝山区| 德清县| 樟树市| 西安市| 平果县| 兴和县| 巴东县| 增城市| 刚察县| 浑源县| 韶山市| 九寨沟县| 静海县| 吉木乃县| 尤溪县| 保山市| 连山| 绵竹市| 池州市| 嘉黎县| 庆安县| 依兰县| 台湾省| 聊城市| 井研县| 巴青县| 平武县| 微山县| 丹东市| 阿拉善左旗| 藁城市| 页游| 马龙县| 徐闻县| 巫溪县| 聂荣县| 登封市| 汕头市| 仪征市|