装饰器: 本质是函数,(装饰其他函数)就是为其他函数添加附加功能。
原则:
1 不能修改被装饰函数的源代码
2 不能修改被装饰函数的调用方式
实现装饰器知识储备:
1 函数即“变量”
2 高阶函数
把一个函数名当做实参传给另外一个函数。
返回值中包含函数名
3 嵌套函数
函数中定义函数。
高阶函数 + 嵌套函数 => 装饰器
#################
不带参数的装饰器:
imort time def run_time(func): def deco(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print("the %s run time is %s" % (func,(stop_time-start_time))) return deco @run_time def test(name,age): time.sleep(2) print(name,age) test(‘xiaoming‘,22) print()
################
带参数的装饰器:
def auth(authtype): print(authtype) def out_wrapper(func): def wrapper(*args,**kwargs): if authtype == ‘a‘: print("wrapper if:", authtype) elif authtype ==‘b‘: print("wrapper elif:",authtype) func(*args, **kwargs) return wrapper return out_wrapper @auth("b") def test1(name,age): print(name,age) test1(‘abc‘,22)
本文出自 “不惧寒冬” 博客,谢绝转载!
原文:http://bujuhandong.blog.51cto.com/1443515/1897505