装饰器说白了,就是在原有的函数上穿一件外套。当你需要需要给自己的业务额外增加功能,比如添加日志、性能测试、事务处理等等,此时可以用装饰器来完成。同时也可以抽取功能相同的代码写成一个装饰器,这样即可减少了代码量,也增加了代码的可读性。下面我将会用五个例题去解释什么叫装饰器。保证你会写装饰器,明白什么是装饰器。
1、装饰器一
这个是一个普通方法之间调用,都给f1,f2函数添加了时间。
import time
def f1():
print("This is a f1")
def f2():
print("This is a f2")
def print_time (func):
print(time.time())
func()
print_time(f1)
print_time(f2)
结果
1536335180.6838505
This is a f1
1536335180.684848
This is a f2
2、装饰器二
这个在装饰器一的基础修改简单的做了修改。在decorator()函数类似于闭包写法,到这边已经到装饰器的核心部分了。
什么是闭包?请访问:https://blog.csdn.net/weixin_43059645/article/details/82229156
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
def name():
print("This is a name")
def name1():
print("This is a name1")
f = decorator(name)
f()
r = decorator(name1)
r()
结果
1536369801.7721543
This is a name
1536369801.7721543
This is a name1
3、装饰器三
@符号是装饰器的语法。程序在运行时,先执行@decorator(@decorator等价于f = decorator(name)),然后先申明wrapper()函数,接着执行在return wrapper,之后在调用wrapper()方法,先打印时间,最后在执行func()(即此时func()函数时你传入进来的name()函数)函数。————这就是一个简单的装饰器写。
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
@decorator
def name():
print("This is a yaoy")
@decorator
def name1():
print("This is a yy")
name()
name1()
结果
1536389069.2313898
This is a yaoy
1536389069.2463503
This is a yy
4、装饰器四
这个实例是装饰器传值,可以传多个值和关键字写法
import time
def decorator(func):
def wrapper(*args,**kw):
print(time.time())
func(*args,**kw)
return wrapper
@decorator
def name(funcname1,funcname2,**kw):
print("This is a " + funcname1)
print("This is a " + funcname2)
print("key word:",kw)
name("yaoy","yy",a=1,b=2,c=3)
结果
1536384602.322565
This is a yaoy
This is a yy
key word: {‘a’: 1, ‘b’: 2, ‘c’: 3}
5、装饰器五
这个实例就是想和大家说,一个函数使用多个装饰器。当有多个装饰器时,装饰器调用的步骤是:自上而下。
import time
def decorator(func):
def wrapper(func_name):
print(time.time())
func(func_name)
return wrapper
def handsome(man):
def who(funcname):
print("yao is a good man")
print("yaoy is a handsome man")
print("yaoy is a nice man")
man(funcname)
return who
@decorator
@handsome
def func(func_name):
print("This is a " + func_name)
func("func")
结果
1536389715.8505254
yao is a good man
yaoy is a handsome man
yaoy is a nice man
This is a func