@contextmanager 另外一种实现上下文的方法(含yield 生成器)

class AAA:

  def __enter__(self):    上文函数

    return slef

  def __exit__(self, exc_type , exc_value , tb):   下文函数

    print  "下文函数,执行关闭连接释放资源"

  def test(self):

    print "执行查询"

with AAA as f:   

  f.test()

原上下文使用见   https://www.cnblogs.com/kaibindirver/p/12688998.html

类和函数(没有设置上下文函数的)

class MyResoure:

  def query(self):

    print("query data")

新方法实现让调用MyResoure类中query函数实现有上下文的方法:

from contextlib import contextmanager

@contextmanager

def make_myresource():

  print("connect to resource")

  yield MyResource()           #这里原来是return 但是函数中遇到return就结束了,不会再返回函数,所以要使用yield (生成器),当他走到这步,再去执行with区域的函数,然后再继续回来这个函数中执行下面一句

  print("close resource connection")

with make_myresource() as r:

  r.query()

输出:

"connect to resource"

"query data"

"close resource connection"

  

猜你喜欢

转载自www.cnblogs.com/kaibindirver/p/12977705.html