Turn: http://blog.csdn.net/thy38/article/details/4471421
I learned the decorator in core Python programming 2nd, which is a completely unfamiliar syntax for me. I did not understand the parser for the first time, so it is necessary to remember it.
At first glance, I thought of the decorator mode in DP, and later I realized that this is not the case at all. (Once again, I despise the impetuous domestic blog. I google it and almost all of them are lock-synchronized decorators and time-out decorators. I admire the original author, however, it is not the same as reprinting, but it is also a great waste of network resources. Maybe the truly valuable blog posts will be lost in this article)
1. What is this?
The book is not very clear. It is similar to Java's AOP (Aspect Oriented Programming, Aspect-Oriented Programming). I don't know anything about AOP. I think it is similarProgramIn design SemanticsForward keyAndRear keyConcept@ PreAnd@ Post). Of course, you can do more in the decorator than the front and back keys, such as introducing logs, adding timing logic to detect performance, and adding transaction capabilities to functions.
In general, the decorator is actually a function, a function used to wrap the function, returns a modified function object, and assigns it a new value to the original identifier, and permanently loses access to the original function object.
2. decorator syntax
(1) No parameter Modifier
[Python] View plaincopy
- DefDeco (func ):
- PrintFunc
- ReturnFunc
- @ Deco
- DefFoo ():Pass
- Foo ()
The first Deco function is a decoration function. Its parameter is the decorated function object. In the Deco function, we can "Decorate" The passed function object and return the object (Remember to returnOtherwise, no function is available in the places where foo is called outside. Actually, foo = Deco (FOO ))
I wrote a small example to check whether the function has any instructions:
[Python] View plaincopy
- DefDeco_functionneeddoc (func ):
- IfFunc. _ Doc _ =None:
- PrintFunc,"Has no _ Doc __, it's a bad habit ."
- Else:
- PrintFunc,':', Func. _ Doc __,'.'
- ReturnFunc
- @ Deco_functionneeddoc
- DefF ():
- Print 'F () Do Something'
- @ Deco_functionneeddoc
- DefG ():
- 'I have a _ Doc __'
- Print 'G () Do Something'
- F ()
- G ()
(2) parameter decorators
[CPP] View plaincopy
- Def decomaker (ARG ):
- 'Usually there are certain requirements for Arg'
- """Because the decorator function with parameters only uses the parameters of the application when calling
- Instead of receiving decorated functions as parameters, you must create them internally.
- A function
- """
- Def newdeco (func): # define a new decorator Function
- Print func, ARG
- ReturnFunc
- ReturnNewdeco
- @ Decomaker (deco_args)
- Def Foo (): Pass
- Foo ()
The first function, decomaker, is a decoration function. Its parameters are used to enhance "enhance decoration. Since this function is not a function object to be decorated, you must create at least one function internally that accepts the decorated function and then return this object (actually Foo = decomaker (ARG) (FOO ))
I really don't have any good examples, but I still have little knowledge. I have to use the synchronization lock example:
[Python] View plaincopy
- DefSynchronized (LOCK ):
- "Lock synchronization decoration method
- ! The lock must implement the acquire and release methods.
- """
- DefSync_with_lock (func ):
- DefNew_func (* ARGs, ** kwargs ):
- Lock. Acquire ()
- Try:
- ReturnFunc (* ARGs, ** kwargs)
- Finally:
- Lock. Release ()
- New_func.func_name = func. func_name
- New_func. _ Doc _ = func. _ Doc __
- ReturnNew_func
- ReturnSync_with_lock
- @ Synchronized(_ Locker)
- DefUpdate (data ):
- "Update scheduled task """
- Tasks =Self. Get_tasks ()
- Delete_task =None
- ForTaskInTasks:
- IfTask [plantask. ID] = data [plantask. ID]:
- Tasks. insert (tasks. Index (task), data)
- Tasks. Remove (task)
- Delete_task = task
- R, MSG =Self. _ Refresh (tasks, delete_task)
- ReturnR, MSG, data [plantask. ID]
The call time is still updae (data ).
At the same time, multiple decorators can be added.CombinationUsage:
[Python] View plaincopy
- @ Synchronized(_ Locker)
- @ Deco_functionneeddoc
- DefF ():
- Print 'F () Do Something'
After learning, I always feel like:The decorator allows the function to be lightly loaded. More importantly, it places the constraints of the function at the interface to make the intent clearer without increasing the caller's burden.
This post is still superficial,I will definitely be back.!