本节内容:
装饰器
装饰器:其实本质就是一个函数
定义:为其它函数增加一个附加的功能
原则:
1、不能修改被装饰函数的源代码
2、不可以修改被装饰函数的调用方式
# 把一个函数当作实参传给另外一个函数(在不修改被装饰函数源代码的情况下为其添加新功能)
现在就来写一个最最简单的装饰器把
def timmer(func):
def warpper(*args,**kwargs):
start_time = time.time()
func()
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()
这样的话,我明明只是调用了test1这个函数,但是函数却有了打印运行时间的功能。
运行test1函数,然后程序找到@timmer后 将test1传给了timmer,然后继续向下运行,在记录了开始时间后,遇到了func(),运行test1函数。
这就是一个比较完整的装饰器
import time
def timer(func):
'''record time'''
def deco():
stat_time = time.time()
func()
stop_time = time.time()
print("the func run time is %s" %(stop_time-stat_time))
return deco
@timer #@timer=timer(test1)
def test1():
time.sleep(3)
print('in the test1')
test1()
下面我们就让装饰器变得通用一点。
比之前的高级一点了,可以接受参数了
import time
def timer(func):
def deco(*args,**kwargs):
stat_time = time.time()
func(*args,**kwargs) #这就变成test1了,在语法糖中把 test1 当成参数传到 timer 中去了
stop_time = time.time()
print("the func run time is %s" %(stop_time-stat_time))
return deco
@timer #@timer=:test1=timer(test1)
def test1():
time.sleep(3)
print('in the test1')
@timer
def test2(name):
time.sleep(3)
print("test2:",name)
test1()
test2('alex')
终极版
import time
user = 'alex'
passwd = 'abc123'
def auth(auth_type):
'''checkpoint function....'''
print("auth func",auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
print("wrepper func args:",*args,**kwargs)
username = input("Username").strip()
password = input("Password").strip()
if user == username and passwd == password:
print("hello")
# func(*args,**kwargs)
return func(*args,**kwargs) #如果像上一行那样用,那么被语法糖装饰的函数会没有 return 值
else:
exit("passwor or username error")
return wrapper
return outer_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()
print(home())
bbs()
8万+

被折叠的 条评论
为什么被折叠?



