什么是装饰器
把一个函数当作参数,返回一个替代版的函数,本质上就是一个返回函数的函数
简单来说就是"在不改变原函数的基础上,给函数增加功能”
例如下面的例子
def func1():
print('hello python')
def outer():
print('~~~~~~~~~~~~~~')
func1()
outer()
如果我们使用装饰器来实现上面的功能~
def func1():
print('hello python')
def outer(a):
def inner():
a()
print('~~~~~~~~~~~~~~~')
return inner
func1 = outer(func1)
func1()
这个装饰器的运行为,将func1函数传给形参a,然后调用a,即func1,然后输出~~~~~~~~~~~,所以输出结果为
下面还有一个例子来帮助大家理解一下装饰器
port time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
@decorator
def f1():
print('This is a function')
f1()
这里的@decorator的意思是调用decorator函数,他下面的函数像当于原函数,而decorator函数相当于修饰元函数(添加功能的)函数
上面这样写,跟下面这样写一样
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
#@decorator
def f1():
print('This is a function')
f1 = decorator(f1)
f1()
这两个函数其运行的过程为,首先将f1传给形参func,然后运行decorator里面的函数,具体为首先输出时间,然后调用f1函数
2.more example
import time
def decorator(func):
def wrapper(*args,**kwargs):
print(time.time())
func(*args,**kwargs)
return wrapper
@decorator
def f1(func_name):
print('This is function ' + func_name)
@decorator
def f2(func_name1,func_name2):
print('This is function ' + func_name1)
print('This is function ' + func_name2)
@decorator
def f3(func_name1,func_name2,**kwargs):
print('This is function ' + func_name1)
print('This is function ' + func_name2)
print(kwargs)
f1('test')
f2('test1','test2')
f3('test1','test2',a=1,b=2,c='westos')
当执行f1('test')的时候,步骤是这样的func_name=test,func=f1('test')。,然后开始调用decorator函数,按照从上到下的运行顺序,先是输出时间,然后是This is function test
当执行f2的时候同理,输出结果为
当执行f3的时候同理,输出结果为
这应该不难理解了,其实就是把原函数当成参数带入修饰函数执行~
ok~