Python一个很好玩的特性decorator

直接上代码,这个例子是从《The Quick Python Book 2ed》里面抄出来的,代码是Python3的。

不用decorator的代码

1 def myfunction(parameter):
2     print(parameter[0])
3 
4 myfunction("hello")

输出如下

h

使用decorator的代码

 1 def dec123(func):
 2     print("in decorate function, decorating", func.__name__)
 3 
 4     def wrapper_func(*args):
 5         print("Executing", func.__name__)
 6         return func(*args)
 7     return wrapper_func
 8 
 9 
10 @dec123
11 def myfunction(parameter):
12     print(parameter[0])
13 
14 myfunction("hello")

输出如下

in decorate function, decorating myfunction
Executing myfunction
h

没有实际项目中使用过,但是,这应该是一个很有用的特性。原函数myfunction打印参数下标0的元素,但是使用decorator的函数,即用dec123修饰的函数myfunction不止运行了原函数本身,还运行了原函数之前和之后的一些“修饰”代码。如果对myfunction的运行结果有怀疑的话,可以用decorator来debug,打印myfunction运行之前的运行状况和myfunction运行之后的运行状况,甚至可以用另一个函数替换myfunction。例如

 1 def dec123(func):
 2     print("in decorate function, decorating", func.__name__)
 3 
 4     def wrapper_func(*args):
 5         print("Executing", func.__name__)
 6         return print(*args)
 7     return wrapper_func
 8 
 9 
10 @dec123
11 def myfunction(parameter):
12     print(parameter[0])
13 
14 myfunction("hello")

将myfunction改为调用print,输出如下

in decorate function, decorating myfunction
Executing myfunction
hello

这样的写法似乎太邪恶了,如果纯粹出于debug的目的也就算了,改完记得把代码还原......

原文地址:https://www.cnblogs.com/valleylord/p/3488886.html