python的装饰器

装饰器的语法

python中有个语法糖,@,

加上@装饰器名称

等同于将下面的函数名传参给装饰器。

例如:

@timmer

def home():

  pass

等同于

home=timmer(home)

如果套上2个装饰器

@auth

@timmer

def index()

  pass

等同于index=auth(timmer(index))

下面具体写一个装饰器的应用:

 1 import time
 2 import random
 3 def timmer(func):  
 4     '''修订一个函数计时装饰器,统计函数执行时间'''
 5     def wrapper(*args,**kwargs):
 6         start=time.time()
 7         res=func(*args,**kwargs) #执行函数
 8         end=time.time()
 9         print('run time is %s' %(start-end)) 
10         return res 
11     return wrapper #记得返回结果
12 
13 @timmer
14 def index():
15     '''被装饰的函数'''
16     print("is's index runing")
17     time.sleep(random.randrange(1,5))
18 
19 index()

装饰器的作用就是:

在不改动原来函数的前提下,对被装饰的函数增加额外的功能,一般是切面功能,比如登录,日志等等。

装饰器的本质就是一个特殊功能的函数。

装饰器传参:

内置装饰器:

未完待续

原文地址:https://www.cnblogs.com/ArmoredTitan/p/7934070.html