Decorator1, decorator1

Source: Internet
Author: User

Decorator1, decorator1

Decorator

 

I. Definition

1. decorator: essentially a function

2. function: used to decorate other functions and add additional functions for other functions

 

Ii. Principles

1. the source code of the decorated function cannot be modified.

2. The call method of the decorated function cannot be modified.

 

3. decorator

1. functions are the concepts of variables.

2. High-Order Functions

3. nested Functions

> Higher-order functions + nested functions = decorator

 

Iv. functions are variables

1. analogy between functions and variables

X = 1 print (id (x) def test (): passprint (test) # output 1842348496 <function test at 0x0000020DBA24D2F0>

In the above example, we define a variable "x" and a function test (). We print the location of the variables and functions in the memory respectively. We can see that when print (test) is print ("function name"), we can print the memory address of the function.

Let's look at the following code:

Def test (): print ("in the test.") f = testf () # output in the test.

Grant the function name test to f and run f (). It can be seen that the function can run normally and is the result of the test function. This is similar to the following code:

X = 1y = xprint (y) # output 1

We can make the following analogy: The function name test is equivalent to x, the function body is equivalent to 1, and f is equivalent to y.

 

2. Memory representation in python

We regard the green square as memory, and each small square is the address of the variable or function in the memory. And the variable name (x) or function name (test), we can visually compare them to the house number. When you need to call a variable or function, you only need to reference their house number to find their memory address and return it. Only the function must be run with (), such as test ().

Since the called variable is actually the memory address of the referenced variable, the called function name can also obtain the memory address of the function body. We can pass the function name to the function as a variable name, that is, the function is a variable. Function as a parameter, that is, a higher-order function.

 

V. High-Order Functions

One of the following conditions is a high-order function.

1. Pass a function name as a real parameter to another function.

2. The returned value contains the function name.

1) function name as a parameter

Import timedef test1 (): time. sleep (2) print ("in the test1.") def test2 (func): start_time = time. time () func () stop_time = time. time () print ("The action time of program is {}". format (stop_time-start_time) test2 (test1) # output in the test1.The action time of program is 2.0012054443359375

In the preceding example, we define a function test1 and a high-level function test2. We passed the test1 function name as a parameter to test2 to implement this function, and added a function for the original test1 function to calculate the running time. This is a bit like a decorator, but it is a bit consistent, that is, the above high-order function test2 has changed the function call method.

However, we have added new functions without modifying the decorated functions.

 

2) the return value contains the function name.

Def test1 (): time. sleep (2) print ("in the test1.") def test2 (func): print (func) return functest1 = test2 (test1) test1 () # output <function test1 at 0x000001E5D853D2F0> in the test1.

In the above example, we finally assigned test2 (test1) to test1 and called test1 again. We can intuitively see that the call method of the test1 function has not changed in this example. However, no new functions are added, and nested functions are required.

 

Vi. nested Functions

The complete definition of another function in the function body is a nested function.

1) Definition:

def foo():print("in the foo")def bar():print("in the bar")bar()foo()

Just calling a function in the function content is not a nested function, as shown below:

def test1():    print("in the test1.")def test2():    test1()

 

2) Scope of nested Functions

Access sequence of local scope and global scope

X = 0def grandpa (): x = 1def dad (): x = 2def son (): x = 3 print (x) son () dad () grandpa () # output 3

 

3) Use nested functions to add new functions to the modified functions 

In the second example of higher-order functions, we implemented the call method without changing the original function. If you need to add a new function, the modification content must exist in the return value, that is, return func. we can define a nested function to implement this function.

Import timedef timer (func): # timer (test1) func = test1def deco (): start_time = time. time () func () # run test1 () stop_time = time. time () print ("the action time of the program is {}". format (stop_time-start_time) return deco # returns the deco memory address def test1 (): time. sleep (2) print ("in the test1.") test1 = timer (test1) test1 () # output in the test1.the action time of the program is 2.0003786087036133

We defined a nested function deco () in timer (), which implements the function of adding runtime for the modified function. The timer () function returns the deco () memory address, which can be referenced and even directly assigned to test1. In this way, we can directly run test1 () to implement the function of Our decorator.

 

7. Decorations

Python adds a modifier name and @ symbol before the function definition to encapsulate the function.

Import timedef timer (func): # timer (test1) func = test1def deco (): start_time = time. time () func () # run test1 () stop_time = time. time () print ("the action time of the program is {}". format (stop_time-start_time) return deco # returns the deco memory address @ timer # test1 = timer (test1) def test1 (): time. sleep (2) print ("in the test1.") test1 ()

  

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.