def count(n):
while n > 0:
yield n #生成值:n
n -= 1
c = count(5) c.__next__() #python 3.4.3要使用c.__next__()不能使用c.next() >>> 5 c.__next__() >>>4
def count(n):
print ( "cunting" )
while n > 0:
yield n #生成值:n
n -= 1
def count(n):
print ("cunting" )
while n > 0:
print ('before yield')
yield n #生成值:n
n -= 1
print ('after yield' )
for i in count(5): print (i),
import time
def tail(f):
f.seek(0,2)#移动到文件EOF
while True:
line = f.readline() #读取文件中新的文本行
if not line:
time.sleep(0.1)
continue
yield line
def grep(lines,searchtext):
for line in lines:
if searchtext in line:
yield line
flog = tail(open('warn.log'))
pylines = grep(flog,'python')
for line in pylines:
print ( line, )
#当此程序运行时,若warn.log文件中末尾有新增一行,且该一行包含python,该行就会被打印出来
#若打开warn.log时,末尾已经有了一行包含python,该行不会被打印,因为上面是f.seek(0,2)移动到了文件EOF处
#故,上面程序实现了tail -f warn.log | grep 'python'的功能,动态实时检测warn.log中是否新增现了
#新的行,且该行包含python
def fibonacci():
a=b=1
yield a
yield b
while True:
a,b = b,a+b
yield b
for num in fibonacci():
if num > 100:
break
print (num),
def read_file(path):
size = 1024
with open(path,'r') as f:
while True:
block = f.read(SIZE)
if block:
yield block
else:
return
>>> def test_return(): ... yield 4 ... return 0 ... File "<stdin>", line 3 SyntaxError: 'return' with argument inside generator
>>> def mygenerator(): ... print 'start...' ... yield 5 ... >>> mygenerator() //在此处调用,并没有打印出start...说明存在yield的函数没有被运行,即暂停 <generator object mygenerator at 0xb762502c> >>> mygenerator().next() //调用next()即可让函数运行. start... 5 >>>
>>> def fun2(): ... print 'first' ... yield 5 ... print 'second' ... yield 23 ... print 'end...' ... >>> g1 = fun2() >>> g1.next() //第一次运行,暂停在yield 5 first 5 >>> g1.next() //第二次运行,暂停在yield 23 second 23 >>> g1.next() //第三次运行,由于之后没有yield,再次next()就会抛出错误 end... Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
>>> def fun():
... print 'start...'
... m = yield 5
... print m
... print 'middle...'
... d = yield 12
... print d
... print 'end...'
...
>>> m = fun() //创建一个对象
>>> m.next() //会使函数执行到下一个yield前
start...
5
>>> m.send('message') //利用send()传递值
message //send()传递进来的
middle...
12
>>> m.next()
None //可见next()返回值为空
end...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有