Iterator在next()中弹出一个list属性并自行充值?

时间:2014-03-09 02:32:46

标签: python iterator

我正在构建一个迭代器类,它从分页搜索结果页面获取它的值。像这样:

class resultsIterator:
    def __init__(self, results, page=1):
        self.results = results
        self.page = page

    def __iter__(self):
        return self

    def next(self):
        if len(self.results):
            return self.results.pop(0)
        else:
            # if results' page is less than expected, get new results
            if self.page < 10:
                # recharge self with new results
                self = self.search(self.page+1)
                return self.next()
            return StopIteration
        pass

    @classmethod
    def search(cls, page=1):
        # at this point i should be scraping off search results
        # from a page and putting them on a list, but
        # to make this simpler, here's a generator instead
        results = [x*page for x in range(10)]
        return cls(results, page)

不幸的是,这不起作用。最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

self = self.search(self.page+1)

仅更改局部变量self的值。它不会更改调用next方法的实例。


而是在self方法中更改search的属性:

def search(self, page=1):
    self.results = [x*page for x in range(10)]
    self.page = page

我认为定义next可能更简单,而不是定义__iter__

def __iter__(self):
    while self.results:
        item = self.results.pop()
        yield item
        if not self.results and self.page < 10:
            self.search(self.page+1)