对我来说更像Python

2024-06-25 06:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的模块是商业软件API的一部分。好消息是有一个python模块-坏消息是它非常不和谐。在

要迭代行,请使用以下语法:

cursor = gp.getcursor(table)
row =  cursor.next()
while row:
    #do something with row
    row = cursor.next()

什么是对付这种情况最具Python式的方法?我考虑过创建一个第一类函数/生成器,并在其中包装对for循环的调用:

^{pr2}$

这是一个进步,但感觉有点笨拙。有没有更像Python的方法?我应该围绕table类型创建一个包装类吗?在


Tags: 模块方法apitable语法docursornext
3条回答

最好的方法是在table对象周围使用Python迭代器接口,imho:

class Table(object):
    def __init__(self, table):
         self.table = table

    def rows(self):
        cursor = gp.get_cursor(self.table)
        row =  cursor.Next()
        while row:
            yield row
            row = cursor.next()

现在你只要打电话:

^{pr2}$

在我看来,这本书可读性很强。在

假设Next和Next中的一个是错别字,而且它们都是相同的,那么您可以使用内置iter函数的不知名变体:

for row in iter(cursor.next, None):
    <do something>

您可以创建一个自定义包装,如:

class Table(object):
    def __init__(self, gp, table):
        self.gp = gp
        self.table = table
        self.cursor = None

   def __iter__(self):
        self.cursor = self.gp.getcursor(self.table)
        return self

   def next(self):
        n = self.cursor.next()
        if not n:
             raise StopIteration()
        return n

然后:

^{pr2}$

另请参见:Iterator Types

相关问题 更多 >