装饰器
Posted liqilong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了装饰器相关的知识,希望对你有一定的参考价值。
函数对修改封闭,对扩展开放
例子:
1.对函数的执行时间进行检测
import time
def foo():
start = time.time()
print(‘foo....‘)
time.sleep(2)
end = time.time()
print(‘spend %s‘ % (end - start))
def test():
start = time.time()
print(‘test....‘)
time.sleep(2)
end = time.time()
print(‘spend %s‘ % (end - start))
foo()
test()
问题:一旦修改,所有函数都会改变,并且对更多的函数进行同样操作的话,就会使代码出现大量的重复
2.改进方法,定义show_time函数
def foo():
print(‘foo....‘)
time.sleep(2)
def show_time(f):
start = time.time()
f()
end = time.time()
print(‘spend %s‘ % (end - start))
show_time(foo)
问题:该方法改变了原生函数的调用方式
3.引入装饰器,装饰器就是为之前的函数添加新的功能
def foo():
print(‘foo....‘)
time.sleep(2)
def test():
print(‘test....‘)
time.sleep(2)
def show_time(f):
def inner():
start = time.time()
f()
end = time.time()
print(‘spend %s‘ % (end - start))
return inner
foo = show_time(foo)
foo()
test = show_time(test)
test()
4.python的优雅写法
def show_time(f):
def inner():
start = time.time()
f()
end = time.time()
print(‘spend %s‘ % (end - start))
return inner
@show_time # test = show_time(test)
def test():
print(‘test....‘)
time.sleep(2)
test() #test执行部分从test到了show_time
5.再次优化
def show_time(f):
def inner(*x, **y):
start = time.time()
f(*x, **y)
end = time.time()
print(‘spend %s‘ % (end - start))
return inner
@show_time
def add(*a, **b):
print(sum(a),sum(b[i] for i in b))
time.sleep(1)
add(1, 2, 5, 6, x=5, y=8)
6.装饰器加参数,直接加入无法传参
def logger(flag=‘‘):
def show_time(f):
def inner(*x, **y):
start = time.time()
f(*x, **y)
end = time.time()
print(‘spend %s‘ % (end - start))
if flag==‘true‘:
print(‘日志记录‘)
return inner
return show_time
@logger(‘true‘) # @show_time
def add(*a, **b):
print(sum(a),sum(b[i] for i in b))
time.sleep(1)
add(1, 2, 5, 6, x=5, y=8)
以上是关于装饰器的主要内容,如果未能解决你的问题,请参考以下文章