1）next方法

2）__iter__方法

>>> i = iter('abc')
>>> i.next()
'a'
>>> i.next()
'b'
>>> i.next()
'c'
>>> i.next()
Traceback (most recent call last):
File "<string>", line 1, in <string>
StopIteration:

class MyIterator(object):
def __init__(self, step):
self.step = step
def next(self):
"""Returns the next element."""
if self.step==0:
raise StopIteration
self.step-=1
return self.step
def __iter__(self):
"""Returns the iterator itself."""
return self
for el in MyIterator(4):
print el
--------------------

3
2
1
0

def fibonacci():
a,b=0,1
while True:
yield b
a,b = b, a+b
fib=fibonacci()
print fib.next()
print fib.next()
print fib.next()
print [fib.next() for i in range(10)]
--------------------

1
1
2
[3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

PEP Python Enhancement Proposal Python增强建议

tokenize模块
>>> import tokenize
>>> tokens.next()
(1, 'class', (1, 0), (1, 5), 'class MyIterator(object):/n')
>>> tokens.next()
(1, 'MyIterator', (1, 6), (1, 16), 'class MyIterator(object):/n')
>>> tokens.next()
(51, '(', (1, 16), (1, 17), 'class MyIterator(object):/n')

def power(values):
for value in values:
print 'powering %s' %value
yield value
for value in values:
if value%2==0:
yield value+3
else:
yield value+2
elements = [1,4,7,9,12,19]
print res.next()
print res.next()
--------------------

powering 1
3
powering 4
7

def psychologist():
while True:
print ("Don't ask yourself too much questions")
print "A that's good, go on"
print "Don't be so negative"
free = psychologist()
print free.next()