Python-装饰器

装饰器:
  • 把一个函数当作参数,返回一个替代版的函数,本质上就是一个返回函数的函数

  • 在不改变原函数的基础上,给函数增加功能

  • 装饰器练习1:
    Python-装饰器
    Python-装饰器

  • 装饰器练习2:在指定位置打印系统运行时间
    1.程序内容:

import time
#写一个装饰器来打印系统运行时间
def decorator(func):  #定义装饰器,指定参数来接受函数
    def wrapper():  #定义真正实现功能的函数
        print(time.time())  #打印系统运行时间
        func()    #调用传进来的函数func
    return wrapper #返回wrapper函数的执行结果,不能省略

@decorator
def f1():
    print('This is a function')

f1()

2.测试:
Python-装饰器
Python-装饰器

  • 装饰器练习3:装饰器接受参数的情况
    1.程序内容:
import time

def decorator(func):
   def wrapper(*args,**kwargs): #接受可变参数和关键字参数
       print(time.time()) #打印系统运行时间
       func(*args,**kwargs)  #调用函数,此处接受的参数必须要与wrapper函数保持一致
   return wrapper

@decorator
def f3(func_name1,func_name2,**kwargs):
   print('This is function ' + func_name1)
   print('This is function ' + func_name2)
   print(kwargs)

f3('test1','test2',a=1,b=2,c='westos')

2.测试:
Python-装饰器
Python-装饰器