Python advanced-closure-decorator, hurry up and take a look

Closure content:

Anonymous function: can complete simple functions, pass the reference of this function, only function

Ordinary function: can complete complex functions, pass the reference of this function, only function

Closure: It can complete more complex functions, pass the function and data in this closure, so the transfer is function + data

Object: able to complete the most complex functions, transfer a lot of data + many functions, so what is transferred is data + functions

Many people learn python and don't know where to start.
Many people learn python, after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
So for these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and course source code!
QQ group: 1097524789

———————————————————

Modify the global function: add global to the function, add nonlocal to the variables outside the closure

Closure definition: There are two functions nested, the inner function can use the parameters transmitted by the outer function, and the last thing that can be passed is the structure and data of the inner function (personal understanding).

Finally, closures can be extended to decorators in python———————————————————

1 def closure():
2 # Define another function inside the function,
3 # And this function uses the variables of the outer function, then call this function and some of the variables used as closure
4 def closure_in(x):
5 print ( '--------- I beat to death -------- S%'% X)
. 6 return closure_in
. 7
. 8 closure X = ()
. 9 X ( 'small strong')
10
. 11 Print ( '*' 20 is)
12 is snacks ----- # ---------
13 is DEF closure_1 (A, B, C):
14 closure_on DEF (X):
15 Print ( ' -----% s snacks ------- '% B)
16 Print (A
X + C)
. 17 return closure_on
18 is
. 19 closure_1 Demo = (2,' small strong ', 3) # closure_1 transfer function
20 demo (4) # clsure_on transfer function
21 is
22 # Note: not bracketed function call function is a function of [itself]; bracketed function, a function call is the result of return.
Decorator content:

The code must comply with the principle of'open and closed'; the functions that have been written should be closed, and the function extension should be open;

1 # The role of the decorator: In order to extend the original code
2 def decoration(func):
3 def call_func():
4 print('-------Decorating-------')
FUNC. 5 ()
. 6 return call_func
. 7
. 8 Decoration @ # # -> demo_new = Decoration (Demo)
. 9 DEF Demo ():
10 Print ( 'Demo ----')
. 11
12 is demo_new = Decoration (Demo)
13 is demo_new ()
Use decorators to test the runtime of a function:

1 import time
2 def set_func(func):
3 def call_func():
4 start_time = time.time()
5 func()
6 stop_func = time.time()
7 print(‘alltimes is %f’ %(stop_func-start_fun))
8 return call_func
9 @set_func
10 def test1():
11 print(‘——-test1———’)
12 test1()
13 ​
14 #等价于:
15 @set_func==test1 = set_func(test1)
16 ​

  1. Functions with no parameters and no return value are decorated:

1 def set_func(func):
2 def call_func():
3 print('———test2——-')
4 print('———-test3——')
5 func()
6 return call_func
7
8 @set_func
9 def test1():
10 print('——test1——-')
2. Decorate functions with parameters and no return values:

1 def set_func(func):
2 def call_func(a): #变
3 print('———test2——-')
4 print('———-test3——')
5 func(a) #变
6 call_func return
. 7
. 8 @set_func
. 9 DEF test1 (NUM):
10 Print ( '-% D --- test1' NUM%)
. 11
12 is test1 (100) -> call_func (100)
13 is test1 (200 is) - >call_func(200)
Reproduce the decorator principle:

————————————————————————-

As long as you encounter the @function decorator (this sentence), it has been executed in the program! !

  1. Function decoration with variable length parameters:

1 def set_func(func):
2 def call_func(*args,**kwargs): #变
3 print('———test2——-')
4 print('———-test3——')
5 func( *args,**kwargs) #(Unpacking) Unpack the
Yuanzu and transfer each one; 6 #func(args,kwargs)—>No, it is equivalent to passing two parameters: a Yuanzu and a dictionary.
7 return call_func
8
9 @set_func
10 def test1(num,*args,**kwargs):
11 print('——test1——- %d '%num)
12 print('——test1——-', args )
13 print('——test1——- ',kwargs)
14
15 test1(100)
16 test1(100,200)
17 test1(100,200,300,mm=100)

Note: *args saves the variable length parameters, which are saved as the original ancestor, **kwargs saves the dictionary form (mm=…)

4. The corresponding return value parameter is decorated, general decorator:

1
#Universal decorator 2 def set_func(func):
3 print("Start decorating————-")
4 def call_func(*args,**kwargs): #变
5 print('———test2——- ')
6 print('————-test3——')
7 return func(*args,**kwargs) #(Unpacking) Unpack the ancestors and transmit each one; if there is no return ret, return none.
8 #func(args,kwargs)—>No, it is equivalent to passing two parameters: a yuan ancestor and a dictionary.
9 return call_func
10
11 @set_func
12 def test1(num,*args,**kwargs):
13 print('——test1——- %d '%num)
14 print('——test1——-', args )
15 Print ( '- --- test1', kwargs)
16 return 'OK' # - returns to the above func () then func-RET return
. 17
18 is RET = test1 (100)
. 19
5. Multiple The decorator decorates the same function:

1 def add_qx(func):
2 print("——Start decorating permissions 1———-")
3 def call_func(*args,**kwargs): #变
4 print('This is permission verification 1')
5 FUNC return (* args, ** kwargs)
. 6 return call_func
. 7
. 8
. 9 DEF add_xx (FUNC):
10 Print ( "- begin xx decorative function ----")
. 11 call_func DEF (* args, ** kwargs ): #变
12 print('This is xx permission verification')
13 return func(*args,**kwargs)
14 return call_func
15
16 @add_qx
17 @add_xx
18 def test1():
19 print('——test1— - ')
20
21 test1 ()
22
first implementation of the first, but the (first principle decorator decorator is not following functions: The following functions must be, otherwise it does), so the first function to wait, After the second decorator is executed, the forming function is handed over to the first decorator; so the running result is:

Start the function of decorating xx,

Start the decoration permission 1,

This is permission verification 1.

This is xx permission verification,

——- test1 ——-,

—————— Decorator Exercise—————- Output Format:

haha

1 def set_func_1(func):
2 def call_func():
3 return ‘

’ + func() + ’


4 return call_func
5
6 ​
7 def set_func_2(func):
8 def call_func():
9 return ‘’ + func() + ’’
10 return call_func
11
12 @set_func_1()
13 @set_func_2()
14 def get_str():
15 return ‘haha’
16
17 print(get_str())

18 The effect of the final execution:

haha


6. Decorate functions with classes (understand):

1 class Test(object):
2 def init (self,func):
3 self.func = fun
4
5 def call (self):
6 print('Here is the function of the decorator...')
7 return self. func()
8
9 @Test
10 def get_str():
11 return'haha '
12
13 print(get_str()) The
above is all the contents of decorators and closures. I hope to gain something. If there is an error, I hope to point it out.

Guess you like

Origin blog.csdn.net/waitingwww/article/details/106999643