统计运行时间的装饰器
带无参数、固定参数、无固定参数的函数
print("分割线".center(50,"="))
import time
def timmer(func):
def wrapper(*args,**kwargs):
start_time=time.time()
res = func(*args,**kwargs) #这里的参数由wrapper函数的参数传递
stop_time=time.time()
print("func run time is %s"%(stop_time-start_time))
return res #返回被装饰函数的返回值return wrapper #返回装饰函数wrapper的内存地址
@timmer #同test1=timmer(test1); # 理解:执行timmer(test1),得到返回值wrapper内存地址,再把wrapper内存地址赋值给test1def test1():
time.sleep(1)
print("my name is test1")
return "test1"
@timmer #同test2=timmer(test2); # 理解:执行timmer(test2),得到返回值wrapper内存地址,再把wrapper内存地址赋值给test2def test2(name,age):
time.sleep(1)
print("my name is %s,I'm %s" %(name,age))
test1() #要配合上面@timmer使用,同timmer(test1)()
print(test1())
test2("chen",40) #要配合上面@timmer使用,同timmer(test2)("chen",40)
print(test2("chen",40))
#结果
my name is test1
func run time is 1.000598430633545
my name is test1
func run time is 1.0012288093566895
test1
my name is chen,I'm 40
func run time is 1.0007030963897705
my name is chen,I'm 40
func run time is 1.0007030963897705
None
页面登录认证
无参装饰器:有参装饰器:user,passwd = "chen","123456"def auth(func):
def wrapper(*args,**kwargs):
username = input("Username: ").strip()
password = input("Password: ").strip()
if user == username and passwd == password:
print("\033[32;1m通过本地认证!\033[0m")
return func(*args,**kwargs)
else:
exit("\033[31;1m错误的用户名或密码\033[0m")
return wrapper
def index():
print("welcome to index page")
@auth
def home():
print("welcome to home page")
return "from home"
@auth
def bbs():
print("welcome to bbs page")
return "from bbs"
index()
home()
bbs()
#结果
welcome to index page
Username: chen
Password: 123456
通过本地认证!
welcome to home page
Username: chen
Password: 123456
通过本地认证!
welcome to bbs pageuser,passwd = "chen","123456"def auth(auth_type):
def outer_wrapper(func):
def wrapper(*args,**kwargs):
if auth_type == "local":
username = input("Username: ").strip()
password = input("Password: ").strip()
if user == username and passwd == password:
print("\033[32;1m通过本地认证!\033[0m")
return func(*args,**kwargs)
else:
exit("\033[31;1m错误的用户名或密码\033[0m")
elif auth_type == "ldap":
print("\033[32;1m远程认证!\033[0m")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") #同home=auth(auth_type="local")(home)def home():
print("welcome to home page")
return "from home"
@auth(auth_type="ldap") #同bbs=auth(auth_type="ldap")(bbs)def bbs():
print("welcome to bbs page")
return "from bbs"
index()
home()
bbs()
#结果
welcome to index page
Username: chen
Password: 123456
通过本地认证!
welcome to home page
远程认证!
def fib(max): n, a, b = 0, 0, 1 while n < max: # print(b) yield b a, b = b, a + b n = n + 1 return "done"fib(5)print(fib(5)) #此时不会获取return的值输出:<generator object fib at 0x04F8AF90>
获取生成器的值:
使用__next__()
print(a.__next__())
print(a.__next__())
print(a.__next__())
f = fib(5)
print(f.__next__())
print(f.__next__())
for、while循环
f = fib(5)
for i in f:
print(i)
应用:
当使用__next__()获取生成器的值的数量超过总的数量时:
def fib(max):
n, a, b = 0, 0, 1
while n < max:
# print(b)yield b
a, b = b, a + b
n = n + 1
return "done" #作为错误提示信息
f = fib(100)
#当获取生成器的值的数量超过总的数量时会报错while True:
x = f.__next__()
print('f:', x)
#解决方式:捕获StopIteration错误while True:
try:
x = f.__next__()
print('f:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
在单线程实现并发运算的效果(携程??)
补充:send()用于给yield传值,但是send传值时,要求生成器已执行到yield语句处(就是send前面至少要有一个__next__(),这样才能保证生成器运行到yield处
import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield #这里的yield由send传值
print("[%s]包子来了,被[%s]吃了!" %(baozi,name))
def producer(name):
c = consumer('A')
c2 = consumer('B')
c3 = consumer('C')
c.__next__()
c2.__next__()
c3.__next__()
print("师傅开始蒸包子啦!")
for i in ["猪肉馅","韭菜馅","白菜馅","豆沙馅"]:
time.sleep(1)
print("%s包子出炉了!"%i)
c.send(i)
c2.send(i)
c3.send(i)
producer("alex")
迭代器
Iterable对象:可以直接作用于for循环的对象统称为可迭代对象
集合数据类型,如list、tuple、dict、set、str等;
生成器generator,包括带yield的generator function。
内置函数:map()、filter()、zip(a,b)
Iterator对象:可以被next()函数调用并不断返回下一个值的对象称为迭代器对象
生成器generator
内置函数:map()、filter()、zip(a,b)
判断一个对象是否是Iterable对象:
#使用isinstance()
>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False
判断一个对象是否是Iterator对象:
#使用isinstance()
>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False