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

2024-04-16 12:27:42 发布

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

这是我的代码,我用它打开一个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

但当我跑的时候:

for x in ExcelReader('excel_sheet'): print x

我收到错误消息:

class is not iterable

Tags: topathinself列表forreadindex
3条回答

你有一些问题。你知道吗

  1. 你的代码没有返回任何东西。调用__work__,但不返回值。

  2. 即使这样做了,也不会有什么帮助,因为从__init__返回的东西不会使对象成为那个东西。

  3. 你不想让你的对象成为一个列表,你只想迭代它。

有关如何用Python编写迭代器的简单示例,请参见this question。你知道吗

此外,在代码中不应该使用双下划线三明治名称,如__work__。按照惯例,这种名称是为Python内部使用而保留的。你知道吗

为了使类可iterable,它需要有一个__iter__方法。你知道吗

考虑:

class Foo(object):
    def __init__(self,lst):
        self.lst = lst
    def __iter__(self):
        return iter(self.lst)

示例:

>>> 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

您的示例似乎更适合作为生成器--我不太明白这里的类需要什么:

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

您应该研究如何实现Python的special iterator methods。你知道吗

另外,请注意,您不应该将方法命名为__work__,因为它使用了magic method语法,但实际上并不是真正的magic方法。你知道吗

相关问题 更多 >