Turn: function decorator of Python)

Source: Internet
Author: User

Function decorator of Python)

 

Apply multiple decoration methods to one method:

@
@ B
@ C
Def F ():

# It is equivalent to the following form. Python calls the decoration method in sequence according to the application order (the last one is called first)
Def F ():
F = A (B (C (F )))

 

Decoration method analysis:

Each decorator is only a method, which can be customized or built-in (for example, the built-in @ staticmethod/@ classmethod ). The decorator method uses the method to be decorated as the input parameter and can perform any operation in the function body (you can imagine that the method is powerful and has many application scenarios ), make sure that an executable function is returned (it can be the original input parameter function or a new function ). The role object of decorator Can Be module-level methods or class methods. Decorator is divided into two types based on the number of parameters used in the application: decorator with no parameter and decorator with parameter. The following sections describe each other.

No parameter decorator:

Def Deco (func ):
"A parameter is required when a decorator declaration is called without a parameter. This parameter will receive the method to be decorated """
Print "Enter decorator" # perform additional operations
Func. ATTR = 'record' # operate a function and add a function attribute.
Return func # Return a callable object (in this example, the return method is used as the input parameter)
# When a new function is returned, the new function can be a global method or an embedded function of the decorator function,
# As long as the function signature is the same as the decorated Function

@ Deco
Def myfunc (): # apply the @ Deco Modifier
Print "Enter myfunc"

Myfunc () # Call the decorated Function

Note: When you use the preceding method to define a decorator method, the extra operations in the function body are only executed when the decorated function is called for the first time, if you want to ensure that the extra operation is executed every time you call the decorated function, you need to replace it with the following statement:

Def Deco (func ):
Def replacefunc (): # defines an embedded function, which encapsulates the decorated function and provides code for additional operations
Print "Enter decorator" # perform additional operations
Return func () # generate a call to the decorated Function
Return replacefunc # since the new embedded function is returned, make sure that each call of the additional operation can run.

@ Deco
Def myfunc (): # apply the @ Deco Modifier
Print "Enter myfunc"

Myfunc () # Call the decorated Function

 

 

The decorator parameter is available:

Def decowithargs (ARG ):
"Because the decorator function with parameters only uses the parameters in use when calling, rather than receiving the decorated functions as parameters,
Therefore, a decorator function must be returned to encapsulate and process the decorated function """
Def newdeco (func): # define a new decorator Function
Def replacefunc (): # define an embedded function in the decorator function to encapsulate specific operations.
Print "Enter decorator" # perform additional operations
Return func () # Call the decorated Function
Return replacefunc
Return newdeco # Return a new decorator Function

@ Decowithargs ("Demo ")
Def myfunc (): # decowithargs
Print "Enter myfunc"

Myfunc () # Call the decorated Function

 

After applying the decoration method to a method, we actually changed the entry point of the function code block referenced by the decoration function name, point it back to the function entry point returned by the decoration method. Therefore, we can use decorator to change the functions of an original function, add various operations, or completely change the original implementation.

Example 11.2 deco. py)

The decorator (and closure) demonstrates that the decorator is only used to wrap the "decoration" (or modifier) function and returns
Modified function objects, assign them to their original identifiers, and permanently lose access to the original function objects.

1 #! /Usr/bin/ENV Python
2
3 from time import ctime, sleep
4
5 def tsfunc (func ):
6 def wrappedfunc ():
7 print '[% s] % s () called' % (
8 ctime (), func. _ name __)
9 return func ()
10 return wrappedfunc
11
12 @ tsfunc
13 def Foo ():
14 pass
15
16 Foo ()
17 sleep (4)
18
19 For I in range (2 ):
20 Sleep (1)
21 Foo ()

Run the script and we get the following output:

[Sun Mar 19 22:50:28 2006] Foo () called
[Sun Mar 19 22:50:33 2006] Foo () called
[Sun Mar 19 22:50:34 2006] Foo () called

Refer:
Http://www.cnblogs.com/jifangliang/archive/2008/07/22/1248313.html
Http://www.x5dj.com/Blog/00182202/00574182.shtml
Http://hi.baidu.com/cricstiano/blog/item/83f9ce732dad7f1b8701b0f3.html

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.