上下文环境:

开始信息

|

中间输出信息

|

结束信息


上下文环境1:

#!/usr/bin/python#-*-coding:utf-8-*-classQuery(object):def__init__(self,name):self.name=namedef__enter__(self):print('Begin')returnselfdef__exit__(self,exc_type,exc_value,traceback):ifexc_type:print('Error')else:print('End')defquery(self):print('Queryinfoabout%s...'%self.name)withQuery('Bob')asq:q.query()Query('Bob').query()

运行结果:

BeginQueryinfoaboutBob...EndQueryinfoaboutBob...


上下文环境2:@contextmanager

fromcontextlibimportcontextmanagerclassQuery(object):def__init__(self,name):self.name=namedefquery(self):print('Queryinfoabout%s...'%self.name)@contextmanagerdefcreate_query(name):print('Begin')q=Query(name)yieldqprint('End')withcreate_query('Bob')asq:q.query()

运行结果:

BeginQueryinfoaboutBob...End


上下文环境3:@contextmanager 再次简化

fromcontextlibimportcontextmanager@contextmanagerdeftag(name):print("<%s>"%name)yieldprint("</%s>"%name)withtag("h2"):print("hello")print("world")

上述代码执行结果为:

<h2>helloworld</h2>


没有上下文环境:@closing 通过closing()来把该对象变为上下文对象,例如,用with语句使用urlopen():

fromcontextlibimportclosingfromurllib.requestimporturlopenwithclosing(urlopen('https://www.baidu.com'))aspage:forlineinpage:print(line)

上述代码执行结果为:

b'<html>\r\n'b'<head>\r\n'b'\t<script>\r\n'b'\t\tlocation.replace(location.href.replace("https://","http://"));\r\n'b'\t</script>\r\n'b'</head>\r\n'b'<body>\r\n'b'\t<noscript><metahttp-equiv="refresh"content="0;url=http://www.baidu.com/"></noscript>\r\n'b'</body>\r\n'b'</html>'


不懂怎么验证的closing

fromcontextlibimportcontextmanager@contextmanagerdefclosing(thing):try:yieldthingfinally:thing.close()

上述代码执行结果为: