一、生成器
列表生成式
a,b = 1,2
a += b #二元运算,a = a + b
a = a+b if b>5 else 0 #三元运算:为真时的结果 if 判定条件 else 为假时的结果
l =[i+1 for i in range(10)] #列表生成式
函数生成器:
在Python中,这种一边循环一边计算的机制,称为生成器:generator。generator保存的是算法,每次调用next(g)
,就计算出g
的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration
的错误。
#-------生成器实现斐波那契数列--------
def func1(max): #函数定义
n,a,b=0,0,1
while n < max:
yield b #包含 yield 关键字的函数,叫做生成器(generator)
a,b=b,a+b #等价于 t = (b,a+b),a = t[0], b=t[1]
n+=1
return "done"
data = func1(10)
print(data)
print(data.__next__()) #调用函数__next__()方法执行
print(data.__next__())
print(data.__next__())
print(data.__next__())
二、迭代器
凡是可作用于for
循环的对象都是可迭代的(Iterable);凡是可作用于next()
函数的对象都是Iterator
类型;集合数据类型如list
、dict
、str
等是Iterable
但不是Iterator
,不过可以通过iter()
函数获得一个Iterator
对象。Python的for
循环本质上就是通过不断调用next()
函数实现的。
from collections import Iterable
from collections import Iterator
isinstance([],Iterable) #判断是否可迭代对象(Iterable),列表、元组、字符串等都是可迭代的
iter_a = iter([]) #将可迭代对象转化为迭代器(Iterator)
isinstance(iter_a,Iterator) #判断是否是迭代器
三、装饰器
装饰器在满足以下条件的情况下,实现原函数不具有的其他功能(如计算运行时间等):
- 不改变原函数的调用方式;
- 不修改原函数代码;
- 不改变原函数的返回值;
import time
#------Universal decorator--------
def deco01(func):
def wrapper(*args, **kwargs):
print("the order NO.3") #多重装饰器调用执行顺序:3
pass
startTime = time.time()
func(*args, **kwargs) #装饰器内调用原函数
endTime = time.time()
print("time is {} ms" .format((endTime - startTime)*1000))
print("the order NO.5") #多重装饰器调用执行顺序:5
return wrapper
def deco02(func):
def wrapper(*args, **kwargs):
print("the order NO.2") #多重装饰器调用执行顺序:2
pass
func(*args, **kwargs) #装饰器内调用原函数
print("the order NO.6") #多重装饰器调用执行顺序:6
pass
return wrapper
@deco02 #装饰器引用,多重装饰器引用的先后对执行顺序有影响
@deco01
def func(a,b):
print("the order NO.4") #多重装饰器调用执行顺序:4
pass
time.sleep(1)
print("the fuction running...")
print("result is %d" %(a+b))
if __name__ == '__main__':
print("the order NO.1") #多重装饰器调用执行顺序:1
func(5,4) #主代码逻辑中调用带装饰器的函数
print("the order NO.7") #多重装饰器调用执行顺序:7
参考文章:
https://blog.csdn.net/xiangxianghehe/article/details/77170585