实现上下文管理
三种方式:
1、enter 和 exit
class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# 异常类型、异常值、异常追踪信息
if exc_type:
print("error")
else:
print("end")
def query(self):
print("query...")
with Query("Tom") as q:
q.query()
"""
enter
query...
end
"""
2、contextmanager
from contextlib import contextmanager
@contextmanager
def tag(name):
print("<%s>"% name)
yield
print("<%s>"% name)
with tag("h1"):
print("hello world")
"""
<h1>
hello world
<h1>
"""
3、closing
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen("http://www.baidu.com")) as page:
print(page.status)
"""
200
"""