在Python中将对象传递到yield语句

时间:2019-06-10 14:22:48

标签: python-3.x

我有一个脚本,可以从数据库发出各种读取请求(我有许多类似于read()方法的方法)。我想避免重复用于创建和关闭游标的代码。所以我在使用上下文管理器和生成器。 (在下面的代码中,db_connection是一个mysql连接器对象。)

from contextlib import contextmanager

class DatabaseReader():
  def __init__(self, db_connection):
    self.db_connection = db_connection
    self.num = num

  @contextmanager
  def connect(self):
    cursor = self.db_connection.cursor(buffered=True)
    try:
      yield
    finally:
      cursor.close()

  def read(self):
    with self.connect():
      cursor.execute("SELECT * FROM table;")

但是,由于未定义AttributeError,因此调用'read'方法会给我一个cursor。如何将游标对象“传递”给yield语句?

1 个答案:

答案 0 :(得分:3)

在自定义实现中,您需要“屈服” cursor对象,该对象将绑定在as语句的with子句中:

您的代码中需要进行3个修复:

  • num传递给self.num = num
  • 屈服cursor
  • as语句中添加with关键字

from contextlib import contextmanager


class DatabaseReader():

    def __init__(self, db_connection, num):
        self.db_connection = db_connection
        self.num = num

    @contextmanager
    def connect(self):
        cursor = self.db_connection.cursor(buffered=True)
        try:
            yield cursor
        finally:
            cursor.close()

    def read(self):
        with self.connect() as cur:
            cur.execute("SELECT * FROM table;")