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

Python closure, decorator, syntax sugar

編輯:Python

Advanced usage of functions , This article will use cases to explain Python Closure 、 Decorator 、 Grammatical sugar .

List of articles

  • Function advanced
    • Closure
    • Decorator
    • Grammatical sugar

Function advanced

We've already learned about functions , We know that when the function is called , The variables defined in the function are destroyed , But sometimes we need to save this variable in the function , Complete some column operations based on this variable every time , such as : Sum with other numbers on the basis of this variable every time , Then what shall I do? ?

We can solve this need through the closure we learn today .

Closure

On the premise of nesting functions , Inner function uses variables of outer function , And the external function returns the internal function , So let's take this Internal functions that use external function variables become closures

Through the definition of closure , We can know the conditions for the formation of closures :

  • Nesting in functions ( Define the function in the function ) Under the premise of
  • Inner function uses variables of outer function ( It also includes the parameters of the external function )
  • The external function returns the internal function

The function of closures :
Closures can hold variables in external functions , It will not be destroyed as the external function is called .

Because the closure refers to the variable of the external function , The variables of the external function are not released in time , Memory consumption .

def out(num1): # Define an external function 
def inner(num2): # Define an internal function 
result = num1 + num2 # The inner function uses the outer function num1
print(" The result is :", result)
return inner # The external function returns the internal function , The internal function returned here is the closure 
# Create closure instances 
f = out(1)
f(2)
f(3)
 The result is : 3
The result is : 4
  • Description of closure execution results :

From the above output results, we can see that the closure saves the variables in the external function num1, Every time a closure is executed num1 = 1 Calculation based on .

A simple example

# External function 
def config_name(name):
# Internal function 
def say_info(info):
print(name + ": " + info)
return say_info
tom = config_name("Tom")
tom(" Hello !")
tom(" Hello , are you there ?")
jerry = config_name("jerry")
jerry(" be not in , Don't play !")
Tom: Hello !
Tom: Hello , are you there ?
jerry: be not in , Don't play !

Closures can also improve code reusability , There is no need to manually define additional functions .


Modify the external function variables used in the closure nonlocal Keyword to complete

def out(num1):
def inner(num2):
# The intention here is to modify the external num1 Value , In fact, it defines a local variable in the internal function num1
nonlocal num1 # Modify external variables num1
num1 = 10
result = num1 + num2
print(f' The result is :{
result}')
return inner
f1 = out(1)
f(2)
 The result is : 12

Decorator

It is a function that adds extra functions to an existing function , It's essentially a closure function .

The features of decorators are :

  1. Do not modify the source code of the existing function
  2. Do not modify the calling method of existing functions
  3. Add extra functionality to existing functions

The basic prototype of the decorator

# def decorator(fn): # fn: Objective function .
# def inner():
# ''' Before executing the function '''
# fn() # Execute the decorated function 
# ''' After executing the function '''
# return inner

example

# Add a login verification function 
def check(fn):
def inner():
print(" Please log in first ....")
fn()
return inner
def comment():
print(" Comment ")
# Use decorators to decorate functions 
comment = check(comment)
comment()
 Please log in first ....
Comment


obviously , It's troublesome to call in this way , Therefore, the concept of grammatical sugar is introduced

Grammatical sugar

Decorator Grammatical sugar How to write it

# Add a login verification function 
def check(fn):
print(" The decorator function executes ")
def inner():
print(" Please log in first ....")
fn()
return inner
# Use syntax sugar to decorate functions 
@check
def comment():
print(" Comment ")
comment()
 The decorator function executes
Please log in first ....
Comment

explain :

@check Equivalent to comment = check(comment)

The execution time of the decorator is executed immediately when the module is loaded .

Code instructions :

  • Closure function has and only has one parameter , Must be a function type , The function defined in this way is the decorator .
  • Write code to follow the principle of open and closed , It stipulates that the implemented function code is not allowed to be modified , But it can be expanded .

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