1、什么是装饰器?
装饰器定义:
把一个函数当作参数,返回一个替代版的函数
本质上就是一个返回函数的函数
装饰器作用:
“在不改变原函数的基础上,给函数增加功能”
需求:在fun函数中添加#行内容
方法一:函数可能被其它模块已经调用,所以不能直接更改原函数
def fun():
#print('Welcome to westos') ##在函数内直接添加
print('Hello python!')
print('Welcome to westos') ##在函数之外添加需求信息,不适用已被调用的函数
fun()
方法二:增加函数,调用时需要改函数名称
def fun():
print('Hello python!')
def fun1():
print('Welcome to westos')
fun()
fun1()
方法三:装饰器
def decorator(fun): ##定义装饰器函数
def wrapper(*args,**kwargs):定义装饰器内部函数
print('Welcome to westos') ##打印输出
fun() ##调用函数
return wrapper
@decorator ##使用装饰器给fun函数添加需求
def fun():
print('Hello python!')
fun()
注意:
decorator是用于返回wrapper(不带()表示返回函数,带()表示返回运行结果)
2、装饰器的调用方式
需求:在函数运行前打印时间
import time
def decorator(fun):
def wrapper():
print(time.time()) ##打印linux系统时