Python装饰器
Posted honel
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python装饰器相关的知识,希望对你有一定的参考价值。
1.Python装饰器原理:
import time #装饰器 def timmer(func): def wrapper(*args, **kwargs): #函数的参数 start_time = time.time() res = func(args, kwargs) #相当于执行test res接受函数的返回值 stop_time = time.time() print(‘运行时间是%s‘ %(stop_time-start_time)) return res #返回func函数的原返回值 return wrapper @timmer #test = timmer(test) def test(name, age): time.sleep(3) print(‘test函数运行完毕,名字为%s,年龄为%s‘ %name %age) return "test函数的返回值" #如果函数带返回值,则在wrapper中应该接收该函数的返回值 #装饰器原理调用: # test = timmer(test) #返回的是wrapper的地址 # test() #相当于执行wrapper() res = test(‘user‘, 18) print(res) #打印返回值
2.Python装饰器(待验证参数):
### 带参数的装饰器 import time #带参数装饰器 def auth(type = ‘db‘): def timmer(func): def wrapper(*args, **kwargs): print(‘装饰器参数类型为:‘,type) #打印装饰器参数 if type == ‘db‘: start_time = time.time() res = func(args, kwargs) stop_time = time.time() print(‘运行时间是%s‘ %(stop_time-start_time)) return res else: print(‘其他类型参数‘) return wrapper return timmer @auth(type=‘db‘) def test(name, age): time.sleep(1) print(‘test函数运行完毕,名字为%s,年龄为%s‘ %name %age) return "test函数的返回值" @auth(type=‘file‘) def test1(name, age): time.sleep(3) print(‘test1函数运行完毕,名字为%s,年龄为%s‘ %name %age) return "test1函数的返回值" test(‘带参数user‘, 18) test1(‘不带参数user‘,20)
note:
"""首尾取值"""
l = [10,4,6,7,8,9,0,3,2]
x,*_,y = l
print(x,y)
"""swap"""
f1 = 101
f2 = 202
f1,f2 = f2, f1
print(f1, f2)
以上是关于Python装饰器的主要内容,如果未能解决你的问题,请参考以下文章