Python编程:contextlib模块实现上下文管理

实现上下文管理

三种方式:

__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
"""

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>
"""

closing

from contextlib import closing
from urllib.request import urlopen

with closing(urlopen("http://www.baidu.com")) as page:
    print(page.status)

"""
200
"""

参考:
廖雪峰python-contextlib

猜你喜欢

转载自blog.csdn.net/mouday/article/details/80690199
今日推荐