Advanced usage of functions , This article will use cases to explain Python Closure 、 Decorator 、 Grammatical sugar .
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 .
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 :
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
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
It is a function that adds extra functions to an existing function , It's essentially a closure function .
The features of decorators are
:
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
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 :