【问题标题】:python generator蟒蛇生成器
【发布时间】:2013-01-27 00:32:39
【问题描述】:

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

问题:

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

检索(self, curs, condition=None)

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

retrieve 方法应该是一个生成器,产生结果集的连续行,直到它完全耗尽。每一行都应该是一个 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

【问题讨论】:

    标签: python sql methods


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2012-02-03
        • 2010-10-27
        • 1970-01-01
        • 2016-07-21
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 2010-10-21
        • 2016-05-28
        相关资源
        最近更新 更多