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

Use of Python closures

編輯:Python

1. Definition and use of closures

When the returned internal function uses the variables of the external function, it forms a closure
Closures can save variables of external functions , It can also improve the reusability of code
Realize the standard format of closures :
1. Nested function
2. Internal functions use variables or parameters of external functions
3. The external function returns the internal function

# @Author : Kant
# @Time : 2022/1/23 17:19
'''
When the returned internal function uses the variables of the external function, it forms a closure
Closures can save variables of external functions , It can also improve the reusability of code
Realize the standard format of closures :
1. Nested function
2. Internal functions use variables or parameters of external functions
3. The external function returns the internal function
'''
# Define a closure
def outer(): # External function
n=1
def inner(): # Internal function
print(n)
# The outer function returns a reference to the inner function ( No parentheses )
return inner
outer() # Calling an outer function does not execute an inner function
# inner() # Inner functions cannot be called directly
ret=outer() # Give a reference to an inner function ret
print(ret)
ret()
# Use of closures
def person(name):
def say(msg):
print(f'{name} say: {msg}')
return say
tom=person('Tom')
rose=person('Rose')
tom('Hello')
rose('World')

2. The inner function of the closure modifies the variables defined by the outer function ( Add nonlocal)

# @Author : Kant
# @Time : 2022/1/23 17:55
def outer():
n=1
def inner():
nonlocal n # No mistake will be reported , list 、 Dictionaries 、 Yuanzu doesn't need to add
n=n+10
print(n)
print(n) # Output 1
return inner
fun=outer()
fun() # Output 11
fun() # Output 21


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