with file('test.py','r') as f :
print f.readline()
#!encoding:utf-8
class echo :
def output(self) :
print 'hello world'
def __enter__(self):
print 'enter'
return self #返回自身实例,当然也可以返回任何希望返回的东西
def __exit__(self, exception_type, exception_value, exception_traceback):
#若发生异常,会在这里捕捉到,可以进行异常处理
print 'exit'
#如果改__exit__可以处理改异常则通过返回True告知该异常不必传播,否则返回False
if exception_type == ValueError :
return True
else:
return False
with echo() as e:
e.output()
print 'do something inside'
print '-----------'
with echo() as e:
raise ValueError('value error')
print '-----------'
with echo() as e:
raise Exception('can not detect')
from contextlib import contextmanager
@contextmanager
def make_context() :
print 'enter'
try :
yield {}
except RuntimeError, err :
print 'error' , err
finally :
print 'exit'
with make_context() as value :
print value
from contextlib import contextmanager
from contextlib import nested
from contextlib import closing
@contextmanager
def make_context(name) :
print 'enter', name
yield name
print 'exit', name
with nested(make_context('A'), make_context('B')) as (a, b) :
print a
print b
with make_context('A') as a, make_context('B') as b :
print a
print b
class Door(object) :
def open(self) :
print 'Door is opened'
def close(self) :
print 'Door is closed'
with closing(Door()) as door :
door.open()
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有