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

Python closure

編輯:Python
""" Closure definition : 1. A closure is a function nested in a function . 2. Closures must be variables of inner functions and outer functions ( Non global variables ) Reference or change of ( Changing immutable data types requires keywords nonlocal Declare in the inner function , Variable data types do not nonlocal Statement , Directly modifying ). Properties of closures : The space of a closure function does not disappear with the end of the function ; Variables that are referenced or changed do not disappear The function of closures : Keep local information not destroyed , Ensure data security . Application of closures : 1、 Some non global variables can be saved but not easily destroyed 、 Changed data . 2、 The essence of ornaments . """
def averageWrapper():
# The space of a closure function does not disappear with the end of the function ; Variables that are referenced or changed do not disappear 
l = []
def averageInner(nums:int):
l.append(nums)
total = sum(l)
return total / len(l)
return averageInner
ret = averageWrapper()
print(ret(10)) # 10.0
print(ret(20)) # 15.0
print(ret(30)) # 20.0
print(ret(40)) # 25.0
# Judge whether a function is a closure : Whether the closure function has free variables 
print(ret.__code__.co_freevars) # ('l',)

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