Python annotator Learning

Source: Internet
Author: User

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

    1. DefDeco (func ):
    2. PrintFunc
    3. ReturnFunc
    4. @ Deco
    5. DefFoo ():Pass
    6. 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

  1. DefDeco_functionneeddoc (func ):
  2. IfFunc. _ Doc _ =None:
  3. PrintFunc,"Has no _ Doc __, it's a bad habit ."
  4. Else:
  5. PrintFunc,':', Func. _ Doc __,'.'
  6. ReturnFunc
  7. @ Deco_functionneeddoc
  8. DefF ():
  9. Print 'F () Do Something'
  10. @ Deco_functionneeddoc
  11. DefG ():
  12. 'I have a _ Doc __'
  13. Print 'G () Do Something'
  14. F ()
  15. G ()

 

 

(2) parameter decorators

 

[CPP] View plaincopy

  1. Def decomaker (ARG ):
  2. 'Usually there are certain requirements for Arg'
  3. """Because the decorator function with parameters only uses the parameters of the application when calling
  4. Instead of receiving decorated functions as parameters, you must create them internally.
  5. A function
  6. """
  7. Def newdeco (func): # define a new decorator Function
  8. Print func, ARG
  9. ReturnFunc
  10. ReturnNewdeco
  11. @ Decomaker (deco_args)
  12. Def Foo (): Pass
  13. 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

  1. DefSynchronized (LOCK ):
  2. "Lock synchronization decoration method 
  3. ! The lock must implement the acquire and release methods. 
  4. """
  5. DefSync_with_lock (func ):
  6. DefNew_func (* ARGs, ** kwargs ):
  7. Lock. Acquire ()
  8. Try:
  9. ReturnFunc (* ARGs, ** kwargs)
  10. Finally:
  11. Lock. Release ()
  12. New_func.func_name = func. func_name
  13. New_func. _ Doc _ = func. _ Doc __
  14. ReturnNew_func
  15. ReturnSync_with_lock
  16. @ Synchronized(_ Locker)
  17. DefUpdate (data ):
  18. "Update scheduled task """
  19. Tasks =Self. Get_tasks ()
  20. Delete_task =None
  21. ForTaskInTasks:
  22. IfTask [plantask. ID] = data [plantask. ID]:
  23. Tasks. insert (tasks. Index (task), data)
  24. Tasks. Remove (task)
  25. Delete_task = task
  26. R, MSG =Self. _ Refresh (tasks, delete_task)
  27. 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

    1. @ Synchronized(_ Locker)
    2. @ Deco_functionneeddoc
    3. DefF ():
    4. 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.!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.