python 装饰器,生成器,迭代器
装饰器
装饰器基本概念
装饰器的定义和作用
装饰的是函数
在不改变原函数的情况下为函数增加其他功能
装饰器构成
函数,嵌套函数,高阶函数
装饰器的使用
@装饰器名字
原函数
在原函数的开头加上装饰器的调用符号
装饰器对于原函数的参数处理
*args -- 将参数变成元组形式
**kwargs -- 将参数变成字典形式
装饰器使用代码
简单使用
# 简单使用 -- 使用装饰器为函数增加一个计算运行时间的功能
import time
def timmer(func):
def warpper(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("the func run time is %s" %(stop_time-start_time))
return warpper
@timmer
def test1():
time.sleep(3)
print("in the test1")
test1()
复杂使用
# 复杂使用 -- 为页面添加 登录验证功能,并且 满足参数需求
import time
user,passwd = 'baobaohui','123456'
def auth(auth_type):
print("auth_type:",auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
print("wrapper func args: ",*args,**kwargs)
if(auth_type == "local"):
username = input("Username: ").strip()
password = input("Password: ").strip()
if (user == username and passwd == password):
print("\033[32;1m User has passed authentication \033[0m")
res = func(*args,**kwargs) # from home
print("---after authentication")
return res
else:
exit("\033[31;1m Invalid username or password \033[0m")
elif(auth_type == "ldap"):
print("不会")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type = "local") #home=wrapper
def home():
print("welcome to home page")
return "from home"
@auth(auth_type = "ldap")
def bbs():
print("welcome to bbs page")
index()
print(home())#wrapper
bbs()
生成器
生成器的基本概念
生成器存在的目的
节省空间,提升效率
生成器的特点
只有在调用时才会生成相应的数据
只记录当前位置
生成器与列表的区别
列表是提前定义并赋值存储好所有的数据
c = [i+2 for i in range(100)
c = [0,2,4,6,8,10...]
生成器保存地址,调用时生成相应数据
c = (i+2 for i in range(100))
生成器使用代码
#斐波那契数列 与 生成器
#只有next 方法
def fibonacci(max):
n,a,b = 0,0,1
while(n<max):
# print(b)
yield b
a,b =b,a+b
n +=1
return "done"
print(fibonacci(10))
f = fibonacci(100)
g = fibonacci(6)
#异常处理
while True:
try:
x = next(g)
print('g: ',x)
except StopIteration as e:
print('Generator return value :',e.value)
break
print("---------------")
print(f.__next__()) #生成器只保留当前数据位置
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
print(f.__next__())
借助生成器完成的单线程并发
#生成器并行
'''
单线程上的 '并发' 执行
异步,协程
'''
import time
def consumer(name):
print("%s 准备吃包子了!" %name)
while True:
baozi = yield # 生成器标志
print("包子 [%s] 来了,被 [%s] 吃了!"%(baozi,name))
c = consumer("baobaohui")
c.__next__()
# b1 = "韭菜馅"
# c.send(b1)
# c.__next__()
def produce(name):
c = consumer('A')
c2 = consumer('B')
c.__next__()
c2.__next__()
print("我开始准备吃包子了!")
for i in range(10):
time.sleep(1)
print("做了1个包子,分两半!")
c.send(i)
c2.send(i)
produce("baobaohui")
迭代器
迭代器基本概念
可迭代对象-Iterable
可以直接作用于for 循环的对象 list,tuple,dict,set,str等
使用 isinstance() 判断一个对象是不是 Iterable 对象
迭代器-Iterator
可以被 next() 函数调用 并不断返回下一个值的对象称为迭代器
生成器都是 Iterator
把 list,dict,str 等 Iterable 变成 Iterator 可使用 iter() 函数
迭代器使用代码
from collections import Iterable
print(isinstance([],Iterable)) #True
isinstance({},Iterable)
isinstance(iter([]),Iterator)
泡泡:
装饰器的使用在以后会比较普遍,生成器和迭代器会少一点。
装饰器中对参数的处理,以及两种参数形式 *args,**kwargs 需要记一下
嗯,就先这样。