0

我有功课,我坚持。我已经尽我所能,但我被卡住了,有人能指出我正确的方向吗......我坚持让每个数据行成为一个新对象。通常我会认为我可以遍历行,但这只会返回最后一行

问题:

修改classFactory.py源码,让build_row函数返回的DataRow类多了一个方法:

检索(自我,curs,条件=无)

self 是(像往常一样)正在调用其方法的实例,curs 是现有数据库连接上的数据库游标,条件(如果存在)是条件字符串,所有接收的行都必须为真。

检索方法应该是一个生成器,产生结果集的连续行,直到它完全耗尽。每行都应该是 DataRow 类型的新对象。

这就是我所拥有的--------测试:

 import unittest
 from classFactory import build_row

 class DBTest(unittest.TestCase):

     def setUp(self):
         C = build_row("user", "id name email")
         self.c = C([1, "Steve Holden", "steve@holdenweb.com"])

     def test_attributes(self):
         self.assertEqual(self.c.id, 1)
         self.assertEqual(self.c.name, "Steve Holden")
         self.assertEqual(self.c.email, "steve@holdenweb.com")

     def test_repr(self):
         self.assertEqual(repr(self.c),
                     "user_record(1, 'Steve Holden', 'steve@holdenweb.com')")

 if __name__ == "__main__":
     unittest.main()

我正在测试的脚本

 def build_row(table, cols):
     """Build a class that creates instances of specific rows"""
     class DataRow:
         """Generic data row class, specialized by surrounding function"""
         def __init__(self, data):
             """Uses data and column names to inject attributes"""
             assert len(data)==len(self.cols)
             for colname, dat in zip(self.cols, data):
                 setattr(self, colname, dat)
         def __repr__(self):
             return "{0}_record({1})".format(self.table, ", ".join(["   {0!r}".format(getattr(self, c)) for c in self.cols]))


DataRow.table = table
DataRow.cols = cols.split()
return DataRow
4

2 回答 2

1

像往常一样遍历行,但使用yield而不是return.

于 2013-01-27T00:59:58.137 回答
1

它应该大致类似于以下内容:

def retrieve(self, curs, condition=None):
    query_ = "SELECT * FROM rows"
    if condition is not None:
        query_ += " %s" %condition
    curs.execute(query_)

    for row in curs.fetchall(): # iterate over the retrieved results
        yield row               # and yield each row in turn
于 2013-01-27T01:00:16.330 回答