>>> import tokenize
>>> reader = open('c:/temp/py1.py').next
>>> tokens=tokenize.generate_tokens(reader)
>>> 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
def adder(values):
for value in values:
print 'adding to %s' %value
if value%2==0:
yield value+3
else:
yield value+2
elements = [1,4,7,9,12,19]
res = adder(power(elements))
print res.next()
print res.next()
--------------------
结果:
复制代码 代码如下:
powering 1
adding to 1
3
powering 4
adding to 4
7
保持代码简单,而不是数据。
注意:宁可有大量简单的可迭代函数,也不要一个复杂的一次只计算出一个值的函数。
例子:
复制代码 代码如下:
def psychologist():
print 'Please tell me your problems'
while True:
answer = (yield)
if answer is not None:
if answer.endswith('?'):
print ("Don't ask yourself too much questions")
elif 'good' in answer:
print "A that's good, go on"
elif 'bad' in answer:
print "Don't be so negative"
free = psychologist()
print free.next()
print free.send('I feel bad')
print free.send("Why I shouldn't ?")
print free.send("ok then i should find what is good for me")
--------------------
结果:
复制代码 代码如下:
Please tell me your problems
None
Don't be so negative
None
Don't ask yourself too much questions
None
A that's good, go on
None