闭包
装饰器
迭代器
生成器
生成器有两种:生成器表达式、生成器函数
# 生成器表达式
# 1.通过for取出生成器里面的数据
gen = (x**2 for x in range(1, 5) if x % 2 == 0)
print type(gen) # <type 'generator'>
for x in gen:
print x # 4 16
# 2.通过next直接取出数据,可以看出生成器是特殊的迭代器
gen = (x**2 for x in range(1, 5) if x % 2 == 0)
print next(gen) # 4
print next(gen) # 16
print next(gen) # 报错:StopIteration
# 3.通过iter取出数据
gen = (x**2 for x in range(1, 5) if x % 2 == 0)
it = iter(gen)
print next(it) # 4
print next(it) # 16
print next(it) # 报错:StopIteration
# 生成器函数
# yield作用:1.函数暂停,2.返回b值
def createNum():
a, b = 0, 1
for i in range(3):
yield b
a, b = b, a+b
gen = createNum()
print type(gen) # <type 'generator'>
# 方式1:
for i in gen:
print i # 1 1 2
# 方式2:
print next(gen) # 1
print next(gen) # 1
print next(gen) # 2
print next(gen) # 报错:StopIteration
# yield作用:1.函数暂停,2.返回b值
def test():
i = 0
while i < 5:
if i == 0:
temp = yield i
print "temp1==>", temp
else:
yield i
print "temp2==>", temp
i += 1
gen = test()
print type(gen) # <type 'generator'>
print next(gen) # 0
# 执行到yield时,test函数作用暂时保存,返回i的值;temp接收下次c.send("python"),send发送过来的值,c.next()等价c.send(None)。
# 相当于把aaa赋值给yield i表达式,然后yield i赋值给temp。
# send()和next()都能让生成器继续向下走一步。
print gen.send("python") # temp1==> python 1
print gen.send("") # temp2==> python 2
# 使用send()需要注意的地方:
# 1.使用send()前先使用next()一次,让程序卡在yield i处。
# 2.如果不先使用next()一次,那么send()参数应为None,即send(None)
# 生成器--完成多任务(协程)
def test1():
while True:
print "--1--"
yield None
def test2():
while True:
print "--2--"
yield None
t1 = test1()
t2 = test2()
while True:
next(t1)
next(t2)