Python decorators to talk about those things, "parameters" of.

I introduced learning Python decorators necessary knowledge and their most basic concepts. Since it is basic knowledge that there is no fundamental, because it was considered that the length is long enough already and knowledge which has been involved in a lot, write a more bound to affect you for your understanding. So the rest of those who remain to this day to write the article if you have not seen before, read the recommendations come back Yo.

00. obtain function parameters

In the last of the last, I wrote an example of a decorator. For convenience, I took it over to you:

Next we look at the use of the Stack class defined above, in the process of using, I found a very strange thing, when I called with the following procedures are normal:

 

And when I like to call the following, the program will error:

You may generate "This is how to be wrong" questions, because as we understand, "keyword arguments" are matched by name, and "location parameters" will be matched in the order parameter is located, since this is the case, admin obviously wear into the username variable, why would you go wrong?

Actually, the reason we suspect the above are not the problem, the problem is that our decorators have written question. Problem is appearing on the parameters passed decorator .

In check_admin this decorator, I get directly from kwargs.get in the username value. The first is correct because I use username keyword arguments passed, then the username of variables and values ​​should in kwargs, the second error is because we pass the username with positional parameters, then the username value appears in the args .

So the new question is, as a user, regardless of location parameter or keyword parameters are right, that we are unable to control, and that this issue should be how to solve it? Python said: "The use  inspect module ." Getcallargs which can solve this problem, it returns a dictionary that holds all the parameters in functions. Plus down we see how the change:

 

01. decorator with parameters

在我们之前熟知的装饰器语法中,外层函数的参数是被装饰的函数,内层函数的参数是被装饰的函数的参数。但是有些时候我们想针对不同的函数装饰器有些变化怎么办,即给装饰器后面带上相应的参数。

比如有个针对加和减的装饰器如下所示:

 

但这个时候我想做点改变,想把函数的名字也给打出来,这个时候我们装饰器肯定就是要带上参数了,参数传的就是函数的名字,这个时候我们该怎么办?其实也简单的很,那就再嵌套一层函数呗。具体如下所示:

其实这么来看,装饰器写起来还是套路满满呢。

今天就到这里就结束啦,不知道你学会了没呢?

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/94762827