What is an adorner?
Let's go first. For example, I wrote a python plugin for use by the user, but I added some features while using it, but I didn't want the user to change the way it was called.
The decorator was used at this time. What is the principle of adorners? We'll take a step at a glance!
If we have a home function as follows:
1 def Home (): 2 Print ' This is the home page! '
And we want the user to verify the permissions before accessing the home function, so you need to call a login function in the home without changing the user's calling method, as in this case:
1 deflogin (usr):2 ifusr = ='Eva_j':3 returnTrue4 defHome ():5result =Login ()6 ifResult:7 Print 'This is the home page!'
This allows us to achieve our needs, but we see that the home code has changed a lot, and all the code is wrapped in an if statement and indented, which is often not what we want to see. So what else can we do?
First we look at a little chestnut:
def Home (): Print ' This is the home page! ' Print Home
Output:<function home at 0x000000000219c978>
We define a home function, but instead of calling it using Home (), let the program print out the address of the home method.
So let's look at this code again:
1 deflogin (usr):2 ifusr = ='Eva_j':3 returnTrue4 defWrapper (funcname):5 ifLogin'Eva_j'):6 returnfuncname7 defHome ():8 Print 'This is the home page!'9 TenHome =Wrapper (Home) OneHome ()
Results of the output:This is the home page!
We can see the finishing touches of this code in this sentence: "Home = wrapper (home)", we have the address of the home function as a parameter passed to the wrapper method, in the wrapper method to verify, After verifying the address of the home method after the return, this then call home, we do not modify the home method, the call home, is not a lot of convenience? This is the concept of adorners!
But soon we found that this method is not good, because the user must add the finishing touch of the code and then execute the home method that was intended to execute, so in Python, it is stipulated that the adorner can use:
1 deflogin (usr):2 ifusr = ='Eva_j':3 returnTrue4 5 defWrapper (funcname):6 ifLogin'AAA'):7 returnfuncname8 9 @wrapperTen defHome (): One print ' This is the home page!'
12
-Home ()
See, we only need to add a "@wrapper" to the home method, you can save the original in the Home () method written before the sentence, so that the convenience of a lot, but also did not change the user's call mode.
However, have you ever thought about how to use adorners to pass parameters?
def Home (usr): Print ' This is the home page! '
python--Decorator