如何使自定义对象可迭代? [英] How to make a custom object iterable?
问题描述
我有一个list
自定义类对象(示例如下).
I have a list
of custom-class objects (sample is below).
使用:list(itertools.chain.from_iterable(myBigList))
我想将所有stations
子列表合并"到一个大列表中.因此,我认为我需要使自定义类成为可迭代的.
Using: list(itertools.chain.from_iterable(myBigList))
I wanted to "merge" all of the stations
sublists into one big list. So I thought I need to make my custom class an iterable.
这是我的自定义类的示例.
Here is a sample of my custom class.
class direction(object) :
def __init__(self, id) :
self.id = id
self.__stations = list()
def __iter__(self):
self.__i = 0 # iterable current item
return iter(self.__stations)
def __next__(self):
if self.__i<len(self.__stations)-1:
self.__i += 1
return self.__stations[self.__i]
else:
raise StopIteration
我实现了__iter__
和__next__
,但似乎没有用.他们甚至没有被召集.
I implemented __iter__
and __next__
but it doesn't seems to work. They're not even called.
任何想法我做错了什么?
Any idea what could I've done wrong?
注意:使用Python 3.3
Note: Using Python 3.3
推荐答案
__iter__
是您尝试遍历类实例时调用的内容:
__iter__
is what gets called when you try to iterate over a class instance:
>>> class Foo(object):
... def __iter__(self):
... return (x for x in range(4))
...
>>> list(Foo())
[0, 1, 2, 3]
__next__
是从__iter__
返回的对象上被调用的对象(在python2.x上,它是next
,而不是__next__
-我一般都对它们都使用别名,以便代码可以与任何一个一起使用...):
__next__
is what gets called on the object which is returned from __iter__
(on python2.x, it's next
, not __next__
-- I generally alias them both so that the code will work with either...):
class Bar(object):
def __init__(self):
self.idx = 0
self.data = range(4)
def __iter__(self):
return self
def __next__(self):
self.idx += 1
try:
return self.data[self.idx-1]
except IndexError:
self.idx = 0
raise StopIteration # Done iterating.
next = __next__ # python2.x compatibility.
这篇关于如何使自定义对象可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!