python 装饰器

一、需求

1 foo():
2     print("执行方法")

遵循开闭原则,即关闭修改,开放扩展。显示函数执行时间。

 1 import time
 2 
 3 
 4 def show_time(func):
 5     def wrapper():
 6         start = time.time()
 7         func()
 8         print("excute cost time %s" % (time.time() - start))
 9         return
10 
11     return wrapper  # 形成闭包函数 wrapper能够调用func
12 
13 
14 @show_time  # foo = show_time(foo)
15 def foo():
16     time.sleep(1)
17     print("执行方法")
18 
19 
20 foo()

二、被装饰函数传参

 1 def detect(func):
 2     def wrapper(x, y):  # 为wrapper传参即为func传参
 3         if type(x) == int and type(y) == int:
 4             return func(x, y)  # func也需接收参数
 5         else:
 6             return print("请使用数字类型数据")
 7 
 8     return wrapper
 9 
10 
11 @detect  # add = detect(add)  add即指向wrapper的内存地址
12 def add(x, y):
13     result = x + y
14     return result
15 
16 
17 add("s", 8)

三、装饰器传参

 1 def show(flag):
 2     if not flag == "True":
 3         return print("该方法不可用")
 4 
 5     def detect(func):
 6         def wrapper(x, y, *args, **kwargs):
 7             if type(x) == int and type(y) == int:
 8                 return func(x, y)
 9             else:
10                 return print("请使用数字类型数据")
11         return wrapper
12     return detect
13 
14 
15 @show("True")  # @show("True")=@detect
16 def add(x, y):
17     result = x + y
18     return result
19 
20 
21 add("s", 8)
原文地址:https://www.cnblogs.com/xu-xiaofeng/p/7751715.html