python 学习 day4
装饰器
定义:本质是函数,目的在于装饰其他函数,就是为其他函数添加附加功能。
原则:不能修改被装饰函数的源代码,不能修改被装饰函数的调用方式。
装饰器的特点:1,高阶函数加嵌套函数 2,函数即变量。
高阶函数
1,把一个函数名当作实参传给另一个函数 2,返回值中包括函数名
def bar(): print("in the bar") def test(func): print(func) func() return func test(bar)
嵌套函数
import time def timer(d): def c(*args,**kwargs): start_time = time.time() d(*args,**kwargs) stop_time= time.time() print("the running time is %s"%(stop_time-start_time)) return c
@ timer # a=timer(a) def a(): time.sleep(3) print("in the a")
@timer # b=timer(b)=c ,b(name)=c(name) def b(name): time.sleep(1) print("------>",name) a() b("wang")
嵌套加高阶函数
#嵌套加高阶 usern,passw = "wang","123456" def auth(auth_type): def out_wrapper(func): def wrapper(*args, **kwargs): if auth_type=="local": username = input("username:") password = input("password:") if username == usern and password == passw: print("\033[32;1mlogging...\033[0m") res = func(*args, **kwargs) return res else: exit("\033[31;1minvalid username or password\033[0m") else: print("好烦啊") return wrapper return out_wrapper def index(): print("welcome to index page") @auth(auth_type="local") def home(): print("welcome to home page") return "from home" @auth(auth_type="ldap") def bbs(): print("welcome to bbs page") index() home() bbs()
生成器
generator,一边计算一边生成,只有在调用时才生成相应的数据,并且只记录当前的数据。
#斐波那契数列 def fix(max): n,a,b=0,0,1 while n<10: print(b) a,b=b,a+b #相当于t=(b,a+b)元组,a=t(0),b=t(1) n=n+1 return"done" fix(10) #斐波那契生成器 def fib(max): n,a,b=0,0,1 while n<10: yield b #yield 即生成器,保持中断状态 a,b=b,a+b #相当于t=(b,a+b)元组,a=t(0),b=t(1) n=n+1 return"done" print(fib(10)) f=fib(10) print(f.__next__()) print(f.__next__()) print(f.__next__())
生成器并行,即携程
import time def consumer(name): print("\033[32;1m[%s]\033[0m准备吃包子啦"%name) while True: baozi=yield print("\033[31;1m%s\033[0m包子来了,\033[32;1m%s\033[1m准备吃了"%(baozi,name)) # c=consumer("小红") # c.__next__() # b1="猪肉大葱" # c.send(b1) def producer(name): c1=consumer("A") #这一步只是变成生成器,并不执行 c2=consumer("B") c1.__next__() c2.__next__() print("我要准备做包子啦!") for i in range(3): time.sleep(2) print("做了两个包子,你们一人一个吧!") c1.send(i) c2.send(i) producer("小红")
迭代器
可迭代对象:
1,集合数据类型,如list,tuple,dict,set,str
2,generator,包括生成器和带yield 的generator function
这些可直接用于for循环的对象称为可迭代对象:Iterable
可用next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
iter()可转换成迭代器