装饰器
装饰器的书写形式如下:
例1:
import time
def check_time(func):
def wrapped():
print("Now time is %s" % time.time())
func()
return wrapped
@check_time
def test():
print("Hello, everyone!")
if __name__ == '__main__':
test()
输出如下:
"C:\Program Files\Python39\python.exe" E:/caicai/test.py
Now time is 1624608574.956126
Hello, everyone!
Process finished with exit code 0
从上段代码可以看出,装饰器就是在不改变原有函数功能的情况下,对该函数增加新的功能处理。
因此,如果需要对很多功能做同样的处理那么就可以使用装饰器,减少代码的重复性。
装饰器可以用在以下方面:
1、日志
2、函数执行时间统计
3、执行函数前预处理
4、执行函数后清理功能
5、权限校验
6、缓存
例1是无参数的函数,那么函数有参数如何写呢?看如下代码所示:
例2 带参数的函数:
import time
def check_time(func):
def wrapped(a, b):
print("Now time is %s" % time.time())
func(a, b)
return wrapped
@check_time
def test(x, y):
a = x + y
print(a)
if __name__ == '__main__':
test(1, 2)
输出:
"C:\Program Files\Python39\python.exe" E:/caicai/test.py
Now time is 1624609290.6499522
3
Process finished with exit code 0
参数不定长
import time
def check_time(func):
def wrapped(*args, **kwargs):
print("Now time is %s" % time.time())
func(*args, **kwargs)
return wrapped
@check_time
def test(x, y, z):
a = x + y + z
print(a)
if __name__ == '__main__':
test(1, 2, 3)
被装饰的函数返回值为return
import time
def check_time(func):
def wrapped(*args, **kwargs):
print("Now time is %s" % time.time())
return func(*args, **kwargs)
return wrapped
@check_time
def test(x, y, z):
a = x + y + z
return a
if __name__ == '__main__':
print(test(1, 2, 3))
函数带有参数,还设置外部变量
def check_time_arg(desc="start analysis..."):
def check_time(func):
def wrapped(*args, **kwargs):
print(desc)
# print("Now time is %s" % time.time())
return func(*args, **kwargs)
return wrapped
return check_time
@check_time_arg("start output...")
def test_one(x, y, z):
a = x + y + z
return a
@check_time_arg()
def test_two(x, y, z):
a = x + y + z
return a
if __name__ == '__main__':
print(test_one(1, 2, 3))
print(test_two(1, 2, 3))
输出:
"C:\Program Files\Python39\python.exe" E:/caicai/test.py
start output...
6
start analysis...
6
Process finished with exit code 0
类装饰器
class Test(object):
def __init__(self, func):
self.__func = func
def __call__(self, *args, **kwargs):
print("========")
return self.__func()
@Test
def test():
return "hello"
a = test()
print(a)
"C:\Program Files\Python39\python.exe" E:/caicai/test.py
========
hello
Process finished with exit code 0
带参数
class Test(object):
def __init__(self, func):
self.__func = func
def __call__(self, *args, **kwargs):
print("========")
return self.__func(*args)
@Test
def test(a, b):
return a + b
c = test(1, 2)
print(c)