What makes something iterable in python
是什么使Python中的某些东西变得不可评价?也就是说,可以用
我可以在python中创建一个不可重写的类吗?如果是这样,怎么办?
型
要使类成为可Iterable,请编写返回迭代器的
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! |
号
该示例使用列表迭代器,但也可以编写自己的迭代器,方法是使
型
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.
号
型
任何使用
此外,任何序列(具有
型
这个问题可以帮助你,它描述了如何使一个交互者
型
您将需要