zoukankan      html  css  js  c++  java
  • 上下文管理contextlib

    contextmanager
    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)
    try:
    yield q
    finally:
    print('End')

    with create_query("zhangsan") as zs:
    zs.query()

    输出

    Begin
    Query info about zhangsan...
    End

    cosling

    返回一个在语句块执行完成时关闭 things 的上下文管理器。这基本上等价于

    from contextlib import contextmanager
    
    @contextmanager
    def closing(thing):
        try:
            yield thing
        finally:
            thing.close()
    from contextlib import closing
    from urllib.request import urlopen
    
    with closing(urlopen('http://www.python.org')) as page:
        for line in page:
            print(line)
  • 相关阅读:
    装饰器模式
    java构建树形节点优化
    excel操作
    回调函数
    网络编程
    小练习-接口发布文章 验证未登录
    requests模块
    try异常处理
    内置函数
    接口-用户登录,返回session
  • 原文地址:https://www.cnblogs.com/jkklearn/p/14227358.html
Copyright © 2011-2022 走看看