程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python closures and decorators

編輯:Python

List of articles

  • One 、python Closure
      • 1. What is a closure
      • 2. Example
  • Two 、 Decorator
      • 1. What is a decorator
      • 2. Application scenarios
      • 3. Example
  • 3、 ... and 、 common python Built in functions
      • 1. map function
      • 2. filter function
      • 3. reduce function
  • summary

One 、python Closure

1. What is a closure

  • Python Functions support nesting . If you scope an external function in an internal function ( Non global scope ) The variables are quoted , Then the inner function will be called closure .
  • Closures need to meet the following requirements 3 Conditions :
    ① Exists in two nested functions , And closures are internal functions ;
    ② The inner function references the variables of the outer function ;
    ③ The external function will return the function name of the internal function .
def outer(start=0):
count=[start]
def inner():
count[0]+=1
return count[0]
return inner
out = outer(5)
print(out())

The specific code trend is as follows

2. Example

Demonstrate built-in functions

def a(): #1 Define external functions 
b=1 #3 External function code 
def c(): #4 Define internal functions 
print(b) #6 Code that executes internal functions 
c() #5 Call the inner function 
a() #2 Call external functions 
# Output results 
1
  • Return the inner function to ( Necessary conditions for closures ), So that the external can access the internal function by receiving the return value
def a():
def b():
return 1 # Define the return value of the internal function as 1
return b # Define the return value of an external function as an internal function 
rst=a() # Accept the return value of an external function , That is, the inner function 
print(rst) #rst It's the internal function 
print(rst()) #rst() Is to call internal functions 
print(a()()) #a()() and rst() identical 
# Output results 
<function a.<locals>.b at 0x0000028BEE117B80>
1
1
  • Use one function as an argument to another function
def a(func_a): # Can pass any function 
print(" Hello , I'm little s!")
func_a() # You can do additional operations on defined functions , There is no need to modify the original function 
print(" Goodbay ")
def b():
print(" Hello , I'm little b!")
a(b)
# Output results 
Hello , I'm little s!
Hello , I'm little b!
Goodbay

demand : Only with a bank card can you perform the remittance operation

# Outside : Create bank card 
# Inside : Remittance operation 
#---------------------------------------------------------------------------------------------------------
def bank(isVIP,action):
if isVIP:
print(" Dear members , welcome !")
else:
print(" Hello! , Here is a new card for you !")
if action=="hui":
def remit():
print(" Remittance operation ")
return remit
if action=="cun":
def cunkuan():
print(" Deposit operation ")
return cunkuan
card=bank(False,"cun")
card()
card()
card()
# Output results 
Hello! , Here is a new card for you !
Deposit operation
Deposit operation
Deposit operation

Two 、 Decorator

1. What is a decorator

  • Suppose we have defined a function , Subsequent may increase temporary demand , For example, insert logs , We can add a wrapping function , It is responsible for these additional requirements , This wrapping function is the decorator .

  • Decorator is a function , It needs to receive a parameter , This parameter represents the modified function . for example , There is a decorator function as follows :

def wrap(func):
print(' Decorating ')
def inner():
print(' Verifying permissions ')
func()
return inner()

Decorator is a nested function , The inner function is a closure , The external function receives the modified function (func)

2. Application scenarios

Decorators are mainly used in the following scenarios :

  • Introducing logs
  • Function execution time statistics
  • Prepare for function execution
  • Clean up after function execution
  • Permission to check
  • cache

3. Example

By adding... Before the function definition @ Symbol and decorator name , Implement the wrapper of the decorator to the function . Add decorators to the following functions , Examples are as follows :

from functools import wraps, reduce
def a(func_a):
print(" The decorator starts to work ")
@wraps(func_a) # Solve the problem of name confusion after being decorated 
def b():
print(" Closures begin to work ")
func_a()
print(" The decorator is finished ")
return b
@a
def abc():
print(" Want to be decorated ")
abc()
print(abc.__name__)
# Output results 
The decorator starts to work
The decorator is finished
Closures begin to work
Want to be decorated
abc

Multiple decorators are applied to a function , The call order is from bottom to top .

def out(args):
def fun(function_name):
print(' Closure ')
def fun_in():
print(args)
return function_name()
return fun_in
return fun
fun=out('hello')
@fun
def test():
print('abc')
a=test()
print(a)
# Output results 
Closure
hello
abc
None

3、 ... and 、 common python Built in functions

1. map function

  • map Function will map the specified sequence according to the function provided .
  • map The function is defined as follows :
map(function, iterable,…)
  • Parameters function Represents the name of the function , Parameters iterable It can be a sequence 、 Containers or iterators that support iteration .

  • map The function is to iterable Each element in calls function function , Save the result returned after each call as an iterator object .

func = lambda x:x+2
result = map(func, [1,2,3,4,5])
print(list(result))
# Output results 
[3, 4, 5, 6, 7]

The execution process is as follows

Example

func=lambda x,y:x+y
rst=map(func,(1,2,3,4,5),[0,7,4,6,8])
for x in rst:
print(x)
# Output results 
1
9
7
10
13

2. filter function

  • filter The filter function performs a filter operation on the specified sequence
  • filter The function is defined as follows :
filter(function,iterable)
  • function The argument can be the name of the function or None; iterable Parameters can be sequences 、 A container or iterator that supports iteration .

Example ①

func = lambda x:x%2
result = filter(func, [1, 2, 3, 4, 5])
print(list(result))
# Output results 
[1, 3, 5]

The execution process is as follows

Example ②

# Return to True Can pass , Otherwise, it can't pass 
func=lambda x:x%2
rst=filter(func,[1,2,3,4,5,6,7,8])
print(list(rst))
# Output results 
[1, 3, 5, 7]

3. reduce function

  • reduce The function accumulates elements in a sequence of parameters
  • reduce The function is defined as follows :
reduce(function, iterable[, initializer])
  • function Is a function with two parameters
  • iterable Is an iterator object
  • initializer Indicates a fixed initial value

Example , demonstration reduce function

from functools import reduce
func=lambda x,y:x+y
rst=reduce(func,[1,2,3,4,5,6,7,8,9,10])
print(rst)
#x,y Represents the previous value and the next value , Add two values 
# Output results 
55

Be careful :
function Parameter cannot be None stay Python3 in ,reduce Functions have been removed from the global namespace , It is now placed in fucntools Module , You need to introduce

The format is as follows :

from functools import reduce

summary

Closure
① One function contains another function
② External function return The internal function name
③ The internal function calls the variable of the external function , This inner function is called a closure
characteristic :
Closures cannot be called directly , Instead, you need to call an external function to get the return value ; Use this return value (), To call internal functions

Decorator
① Receive the function name in the parameter section of the external function
② Call the function corresponding to the parameter in the function body of the internal function
③ The external function returned the internal function name
④ Call an external function to pass in the function name to get the return value ( Closure )
⑤ Call... Through a closure , Realize the function call corresponding to the parameter
⑥ Can pass @ Name of decorator , To replace the process of transferring parameters

characteristic :
The call of decorator is relatively safe and reliable , And will not change the logic of the original function


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved