Python with用法实例
python中with可以明显改进代码友好度,比如:
withopen('a.txt')asf:
printf.readlines()
为了我们自己的类也可以使用with,只要给这个类增加两个函数__enter__,__exit__即可:
>>>classA:
def__enter__(self):
print'inenter'
def__exit__(self,e_t,e_v,t_b):
print'inexit'
>>>withA()asa:
print'inwith'
inenter
inwith
inexit
另外python库中还有一个模块contextlib,使你不用构造含有__enter__,__exit__的类就可以使用with:
>>>fromcontextlibimportcontextmanager >>>from__future__importwith_statement >>>@contextmanager ...defcontext(): ... print'enteringthezone' ... try: ... yield ... exceptException,e: ... print'withanerror%s'%e ... raisee ... else: ... print'withnoerror' ... >>>withcontext(): ... print'----incontextcall------' ... enteringthezone ----incontextcall------ withnoerror
使用的最多的就是这个contextmanager,另外还有一个closing用处不大
fromcontextlibimportclosing
importurllib
withclosing(urllib.urlopen('http://www.python.org'))aspage:
forlineinpage:
printline
热门推荐
8 图书馆简短祝福语
10 牛年大气简短的祝福语
11 年底了祝福语简短的
12 牛年公司新年祝福语简短
13 新单位成立祝福语简短
14 国庆中秋祝福语大全简短
15 幼师离别祝福语老师简短
16 学校校长新年祝福语简短
17 生日祝福语宿舍舍友 简短
18 生日奶茶红包祝福语简短