zoukankan      html  css  js  c++  java
  • 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)
    #需要一个过程化的方法,如果说有需要销毁资源的地方,就写在yield之后。
    @contextmanager
    def create_query(name):
        print('Begin')
        q = Query(name)
        yield q
        print('End')
    #把这个当做资源来使用with
    with create_query('Bob') as q:
        q.query()

    我比较喜欢这种。__enter__()和__exit__()方法却有一个优势就是可以整合成为完全的面向对象的方式。而上面这种,似乎看起来只能是面向过程的

    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()
  • 相关阅读:
    LeetCode 172. Factorial Trailing Zeroes
    C++primer 练习12.27
    C++primer 练习12.6
    C++primer 练习11.33:实现你自己版本的单词转换程序
    77. Combinations
    75. Sort Colors
    74. Search a 2D Matrix
    73. Set Matrix Zeroes
    71. Simplify Path
    64. Minimum Path Sum
  • 原文地址:https://www.cnblogs.com/sunyuw/p/8390881.html
Copyright © 2011-2022 走看看