什么使python中的东西可迭代

What makes something iterable in python

本问题已经有最佳答案,请猛点这里访问。

是什么使Python中的某些东西变得不可评价?也就是说,可以用for循环它。

我可以在python中创建一个不可重写的类吗?如果是这样,怎么办?


要使类成为可Iterable,请编写返回迭代器的__iter__()方法。例子

1
2
3
4
5
6
7
8
9
class MyList(object):
    def __init__(self):
        self.list = [42, 3.1415,"Hello World!"]
    def __iter__(self):
        return iter(self.list)

m = MyList()
for x in m:
    print x

印刷品

1
2
3
42
3.1415
Hello World!

该示例使用列表迭代器,但也可以编写自己的迭代器,方法是使__iter__()成为生成器,或者返回定义next()方法的迭代器类的实例。


python文档正是这样描述的:

One method needs to be defined for container objects to provide iteration support:

1
container.__iter__()

Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:

1
iterator.__iter__()

Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

1
iterator.next()

Return the next item from the container. If there are no further items, raise the StopIteration exception. This method corresponds to the tp_iternext slot of the type structure for Python objects in the Python/C API.


任何使用__iter__()方法的对象都被认为是不可迭代的。

此外,任何序列(具有__getitem__()方法的对象)都可以返回迭代器。迭代器是一个带有__next__()方法的对象,该方法返回序列中的下一个对象并引发stopIteration异常。


这个问题可以帮助你,它描述了如何使一个交互者


您将需要next()__iter__()方法。这里有一个很好的小教程。