1.抛砖引玉
任何对象,只要正确实现了上下文管理,就可以用于with语句。
实现上下文管理是通过enter和exit这两个方法实现的。例如,下面的class实现了这两个方法:
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print('Begin')
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
def query(self):
print('Query info about %s...' % self.name)
with Query('Bob') as q:
q.query()
运行结果:
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Python全网练习/常用内置模块.py
Begin
Query info about Bob...
End
Process finished with exit code 0
2.@contextmanager
1)编写enter和exit仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下:
from contextlib import contextmanager
class Query(object):
def __init__(self, name):
self.name = name
def query(self):
print('Query info about %s...' % self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
yield q
print('End')
with create_query('Bob') as q:
q.query()
运行结果:
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Python全网练习/常用内置模块.py
Begin
Query info about Bob...
End
Process finished with exit code 0
2)很多时候,我们希望在某段代码执行前后自动执行特定代码,也可以用@contextmanager实现。例如:
from contextlib import contextmanager
@contextmanager
def tag(name):
print("<%s>" % name)
yield
print("</%s>" % name)
with tag("h1"):
print("hello")
print("world")
运行结果:
"C:\Program Files\Python36\python.exe" C:/Users/Administrator/PycharmProjects/Python全网练习/常用内置模块.py
<h1>
hello
world
</h1>
Process finished with exit code 0
3.@closing
如果一个对象没有实现上下文,我们就不能把它用于with语句。这个时候,可以用closing()来把该对象变为上下文对象。例如,用with语句使用urlopen():
from contextlib import contextmanager
from contextlib import closing
from urllib.request import urlopen
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
with closing(urlopen('http://www.baidu.com')) as page:
for line in page:
print(line)