为什么返回列表的类不会迭代?

use*_*204 1 python iterator class python-2.7

这是我的代码,我用它来打开excel表,然后将每行作为字符串列表返回(其中每个单元格都是一个字符串).该类返回一个列表,该列表填充了与文件中的行一样多的列表.所以50行将返回50个列表.

from xlrd import open_workbook

class ExcelReadLines(object):

    def __init__(self,path_to_file):
        '''Accepts the Excel File'''
        self.path_to_file = path_to_file
        self.__work__()


    def __work__(self):
        self.full_file_as_read_lines = []
        self.book = open_workbook(self.path_to_file)
        self.sheet = self.book.sheet_by_index(0)

        for row_index in range(self.sheet.nrows):
            single_read_lines = []
            for col_index in range(self.sheet.ncols):
                cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
                cell_value_stripped = cell_value_as_string.strip('u')
                single_read_lines.append(cell_value_stripped)
            self.full_file_as_read_lines.append(single_read_lines)

        return self.full_file_as_read_lines
Run Code Online (Sandbox Code Playgroud)

但是当我跑步时:

for x in ExcelReader('excel_sheet'): print x
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:

class is not iterable
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 7

为了使类可迭代,它需要有一个__iter__方法.

考虑:

class Foo(object):
    def __init__(self,lst):
        self.lst = lst
    def __iter__(self):
        return iter(self.lst)
Run Code Online (Sandbox Code Playgroud)

例:

>>> class Foo(object):
...     def __init__(self,lst):
...         self.lst = lst
...     def __iter__(self):
...         return iter(self.lst)
... 
>>> Foo([1,2,3])
<__main__.Foo object at 0xe9890>
>>> for x in Foo([1,2,3]): print x
... 
1
2
3
Run Code Online (Sandbox Code Playgroud)

你的例子看起来好像作为一个发电机会好一点 - 我真的不明白这里的课程需要什么:

def excel_reader(path_to_file):
    book = open_workbook(path_to_file)
    sheet = book.sheet_by_index(0)

    for row_index in range(sheet.nrows):
        single_read_lines = []
        for col_index in range(sheet.ncols):
            cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
            cell_value_stripped = cell_value_as_string.strip('u')
            single_read_lines.append(cell_value_stripped)
        yield single_read_lines
Run Code Online (Sandbox Code Playgroud)