Let's talk about the decorator of py and the decorator of py.
It was very mysterious to know that there was such a decoration device.
Including c # and java,
C # is called the attribut feature, and java is calledAnnotationNote: When I secretly studied the c # tutorial, I admitted that I watched the pirated video and talked about it with the above lecturer. So I think it is very high, if you do not talk about these two languages, simply say python.
It is very easy to implement this in python. Of course, if this syntax is supported, the method is the same.
Many programmers like to make simple things complicated. For example, I have said so many things and have not yet reached the topic. I just want to make it too simple ,.
I want to figure out a few questions. It's easy to talk about this.
1. decorator and decorated Functions
2. Parameters of the decorator, parameters of the decorator Function
3. Return Value of the decorated Function
4. Parameters of the decorator
5. Return Value of the decorator
There are regulations to explain these issues:
1 def task_log(task): 2 print(task) 3 def decorator(*a, **k): 4 print(a) 5 print(k) 6 return task(*a, **k) 7 return decorator 8 9 @task_log10 def test(a):11 print(a)12 return a
Obviously
1. task_log this is a decorator, and test is a decorated function.
2. the modifier parameter is the task function, and the decorated parameter is.
3. the return value of the decorated function is a. the decorator returns a decorator function.
The calling process is a little complicated, but it is not difficult to understand,
1. Call the test function.
2. the decorator is called first.
3. the decorator returns a copy of the function.
4. This copy is actually called.
5. We have called this function in the copy.
6. Everything is complete. It seems that a remarkable process has been implemented.
Here is the py decorator. The other two languages are basically the same, so it is required in attribute orAnnotationTo realize the invoke method, or an interface, and wait for the program to call it. In essence, you still need to call the original function in this class or method. Of course, please make an axe if it is not correct.
However, in py:
Decorator execution sequence
Finally, a version with parameters is provided.
1 def task_log_para(para):2 print(para)3 def wrapping(task):4 def decorator(*a,**k):5 print(a)6 print(k)7 return task(*a,**k)8 return decorator9 return wrapping
After-school thinking
1. Parameters of the decorator
2. Return Value of the decorator
3. execution sequence of the decorator