1 入门 10分钟搞明白
https://www.bilibili.com/video/av25698102
def decorator(func):
def wrapper():
t1 = time.time()
func()
t2 = time.time()
print(t2-t1)
return wrapper
2 相对较详细介绍 廖大大
有一个小练习可以做一下
还有对import functools的用法简单介绍【待仔细理解】
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014318435599930270c0381a3b44db991cd6d858064ac0000
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s():' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
3 详解Python的装饰器
https://www.cnblogs.com/cicaday/p/python-decorator.html
可以用第一个例子做练习,里面介绍了原理,还包含了可能会有的使用装饰器会产生的错误(还没完全理解错误场景)。
python 2.4后面版本的Python中支持了@语法糖
Q:1 程序员B用的库主要实现一些什么功能?
def log(text):
def decorate(func):
def wrapper(*args,**wk):
print text,func.__name__
func()
return wrapper
return decorate
@log('[DEBUG]: Enter')
def say_hello():
print "hello!"
@log('[DEBUG]: Enter')
def say_goodbye():
print "hello!" # bug here
if __name__ == '__main__':
say_hello()
say_goodbye()
装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象。它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码并继续重用
个人总结:
用例:对函数过程计时,代码运行注释,插入日志、性能测试、事务处理、缓存、权限校验等场景
练习:对函数加日志信息,计时练习