http://www.rafekettler.com/magicmethods.html
http://stackoverflow.com/questions/19151/build-a-basic-python-iterator
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
for c in Counter(3, 8):
print c
This will print:
3
4
5
6
7
8
This is easier to write using a generator, as covered in a previous answer:
def counter(low, high):
current = low
while current <= high:
yield current
current += 1
for c in counter(3, 8):
print c
2
http://stackoverflow.com/questions/4019971/how-to-implement-iter-self-for-a-container-object-python
I normally would use a generator function. Each time you use a yield statement, it will add and item to the sequence.
This would create an iterator that returns five, and then every item in some_list.
def __iter__(self):
yield 5
for x in some_list:
yield x
3
python how to call __iter__ of base class? - Google Search
http://stackoverflow.com/questions/6560354/how-would-i-create-a-custom-list-class-in-python
Your can subclass
list
if your collection basically behaves like a list:class MyCollection(list):
def __init__(self, *args, **kwargs):
super(MyCollection, self).__init__(args[0])
However, if your main wish is that your collection supports the iterator protocol, you just have to provide an
__iter__
method:class MyCollection(object):
def __init__(self):
self._data = [4, 8, 15, 16, 23, 42]
def __iter__(self):
for elem in self._data:
yield elem
This allows you to iterate over any instance of
MyCollection
.http://www.boduch.ca/2009/02/custom-python-iterators.html
No comments:
Post a Comment