@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区域的函数,然后再继续回来这个函数中执行下面一句    #原来 函数中 return 和 yield 后面其实不用返回东西也可以

  print("close resource connection")

 

with make_myresource() as r:

  r.query()

 

输出:

"connect to resource"

"query data"

"close resource connection"

 

 

yield不返回的例子

 

 

例子: https://www.cnblogs.com/kaibindirver/p/13029791.html 

posted @ 2020-05-28 00:33  凯宾斯基  阅读(220)  评论(0编辑  收藏  举报