网站导航网,网络服务合同定义,做网站网页需要什么技术,宁波做网站1、 什么是闭包#xff1f;
如果一个函数内部定义了另一个函数#xff0c;并且内部函数引用了外部函数的变量#xff0c;那么内部函数就形成了一个闭包。
def outer_function(x):# 外部函数接受一个参数 x 是自由变量# seed 也是一个自由变量seed 10def inner_function(y…1、 什么是闭包
如果一个函数内部定义了另一个函数并且内部函数引用了外部函数的变量那么内部函数就形成了一个闭包。
def outer_function(x):# 外部函数接受一个参数 x 是自由变量# seed 也是一个自由变量seed 10def inner_function(y):# 内部函数接受另一个参数 yreturn x y seedreturn inner_function# 创建闭包函数传入参数 10closure就是一个闭包
closure outer_function(10)# 使用闭包函数计算 5 10 10
result closure(5)
print(result) # 输出 25
2、自由变量
https://docs.python.org/zh-cn/3.7/reference/executionmodel.html#index-6 局部变量如果名称绑定在一个代码块中则为该代码块的局部变量。 全局变量如果名称绑定在模块层级则为全局变量。 自由变量如果变量在一个代码块中被使用但不是在其中定义则为 自由变量。
3、闭包的特点
1、 闭包可以**捕获即使外部函数已经执行完毕这些变量依然可以被内部函数访问和操作外部变量**并且保持外部变量的状态使其在多次调用中保持不变。 2、闭包允许函数返回一个函数而不仅仅是一个值。 3、闭包与闭包之间的状态是隔离的
def average():data [] # 使用列表来存储内部状态def add_number(number):data.append(number) # 将新数字添加到列表中total sum(data) # 计算列表中所有数字的总和count len(data) # 获取列表中数字的数量return total / count if count 0 else 0 # 计算平均数return add_number# 创建累计平均数的闭包
avg average()# 不断添加新的数字并计算平均数
# data变量是average函数的局部变量
# 但是 当调用avg(10)时average函数已经执行完了所以它的作用域已经不存在了
print(avg(10)) # 平均数: 10.0
print(avg(20)) # 平均数: 15.0
print(avg(30)) # 平均数: 20.0
print(avg -- , avg(40)) # 平均数: 25.0# 闭包和闭包之间的状态是隔离的
avg1 average()
print(avg1 -- , avg1(11))
print(avg1 -- , avg1(15))
4、闭包的应用
本地作用域在函数结束后就立即失效而嵌套作用域在嵌套的函数返回后却仍然有效类似可以把这些变量类比为 C中局部静态变量。想要给函数增加或者保持状态、实现装饰器、构建工厂函数、创建函数组合就可以使用闭包来实现。
##################### 函数组合
def add(x):return x 2def multiply(x):return x * 3def compose(f, g):# 返回一个闭包将 f(g(x)) 的结果def inner(x):return f(g(x))return inner# 创建函数组合
combined_function compose(add, multiply)# 使用组合函数
result combined_function(4) # 先执行 multiply(4)然后执行 add(12)
print(result) # 输出 14################### 创建工厂函数
def create_multiplier(factor):# 工厂函数返回一个闭包def multiplier(x):return x * factorreturn multiplier# 创建两个不同的乘法函数工厂
double create_multiplier(2)
triple create_multiplier(3)# 使用工厂函数生成乘法函数
double_result double(5) # 返回 5 * 2 10
triple_result triple(5) # 返回 5 * 3 15print(double_result)
print(triple_result)################# 装饰器
import timedef timing_decorator(func):def wrapper(*args, **kwargs):start_time time.time()result func(*args, **kwargs)end_time time.time()execution_time end_time - start_timeprint(f{func.__name__} executed in {execution_time:.4f} seconds)return resultreturn wrapper# 使用装饰器
timing_decorator
def requests_http_data():# 模拟一些耗时操作time.sleep(2)requests_http_data()
5、global和nonlocal
global 声明对全局变量进行引用修改 nonlocal 内嵌函数内部想对嵌套作用域中的值是不可变类型的变量值为 int、float、str进行修改
n 100def add():global n # 函数内部要对全局变量进行修改必须使用global声明n n 100print(n)add()
print(n)def sub():a 100def execs():nonlocal a # 内嵌的函数想修改外部函数的变量必须使用nonlocal进行声明a a - 1return areturn execss sub()
print(s())6、闭包和类
闭包比较像只有一个方法的类可以保持状态和数据隐藏为什么不写成类 1、闭包的功能一般很小很简单 2、闭包执行速度较快不需要多余的self参数等
# 闭包
def counter():count 0def increment():nonlocal countcount 1return countreturn increment# 创建闭包对象
counter1 counter()
counter2 counter()print(counter1()) # 输出 1
print(counter1()) # 输出 2
print(counter2()) # 输出 1
print(counter1()) # 输出 3# 类
class Counter:def __init__(self):self.count 0def increment(self):self.count 1return self.count# 创建类对象
counter1 Counter()
counter2 Counter()print(counter1.increment()) # 输出 1
print(counter1.increment()) # 输出 2
print(counter2.increment()) # 输出 1
print(counter1.increment()) # 输出 37、扩展-偏函数
# 偏函数也可以保持函数内部的变量状态
# 我们可以使用内置的 functools 模块的 partial 函数来创建偏函数。
# 偏函数指通过固定函数的一部分参数后返回一个新的函数
# 这个新函数可以接受剩余的参数进行调用
from functools import partialdef add(a, b):return a bx partial(add, 1) # 1赋给参数a 并暂停函数
print(x)
res1 x(2) # 将2赋给b后进行计算
print(res1) # 3
res2 x(3)
print(res2) # 4
文章转载自: http://www.morning.tlrxp.cn.gov.cn.tlrxp.cn http://www.morning.bpmdx.cn.gov.cn.bpmdx.cn http://www.morning.pzcjq.cn.gov.cn.pzcjq.cn http://www.morning.zlkps.cn.gov.cn.zlkps.cn http://www.morning.madamli.com.gov.cn.madamli.com http://www.morning.ljtwp.cn.gov.cn.ljtwp.cn http://www.morning.xrftt.cn.gov.cn.xrftt.cn http://www.morning.dwhnb.cn.gov.cn.dwhnb.cn http://www.morning.yrjfb.cn.gov.cn.yrjfb.cn http://www.morning.bypfj.cn.gov.cn.bypfj.cn http://www.morning.zztkt.cn.gov.cn.zztkt.cn http://www.morning.fhkr.cn.gov.cn.fhkr.cn http://www.morning.qhln.cn.gov.cn.qhln.cn http://www.morning.wjyyg.cn.gov.cn.wjyyg.cn http://www.morning.kcnjz.cn.gov.cn.kcnjz.cn http://www.morning.jjxxm.cn.gov.cn.jjxxm.cn http://www.morning.fktlg.cn.gov.cn.fktlg.cn http://www.morning.vehna.com.gov.cn.vehna.com http://www.morning.lprfk.cn.gov.cn.lprfk.cn http://www.morning.xxrwp.cn.gov.cn.xxrwp.cn http://www.morning.qgkcs.cn.gov.cn.qgkcs.cn http://www.morning.gqddl.cn.gov.cn.gqddl.cn http://www.morning.dmcqy.cn.gov.cn.dmcqy.cn http://www.morning.tdscl.cn.gov.cn.tdscl.cn http://www.morning.fmkjx.cn.gov.cn.fmkjx.cn http://www.morning.msbct.cn.gov.cn.msbct.cn http://www.morning.sfcfy.cn.gov.cn.sfcfy.cn http://www.morning.lmnbp.cn.gov.cn.lmnbp.cn http://www.morning.bpmtj.cn.gov.cn.bpmtj.cn http://www.morning.thrcj.cn.gov.cn.thrcj.cn http://www.morning.wjlhp.cn.gov.cn.wjlhp.cn http://www.morning.hxxyp.cn.gov.cn.hxxyp.cn http://www.morning.rpwm.cn.gov.cn.rpwm.cn http://www.morning.gprzp.cn.gov.cn.gprzp.cn http://www.morning.rjkfj.cn.gov.cn.rjkfj.cn http://www.morning.hwlk.cn.gov.cn.hwlk.cn http://www.morning.txysr.cn.gov.cn.txysr.cn http://www.morning.qtzqk.cn.gov.cn.qtzqk.cn http://www.morning.qsmch.cn.gov.cn.qsmch.cn http://www.morning.fhsgw.cn.gov.cn.fhsgw.cn http://www.morning.clhyj.cn.gov.cn.clhyj.cn http://www.morning.dwdjj.cn.gov.cn.dwdjj.cn http://www.morning.cfnht.cn.gov.cn.cfnht.cn http://www.morning.dkbgg.cn.gov.cn.dkbgg.cn http://www.morning.jczjf.cn.gov.cn.jczjf.cn http://www.morning.gcbhh.cn.gov.cn.gcbhh.cn http://www.morning.clpfd.cn.gov.cn.clpfd.cn http://www.morning.psyrz.cn.gov.cn.psyrz.cn http://www.morning.pxwzk.cn.gov.cn.pxwzk.cn http://www.morning.ndlww.cn.gov.cn.ndlww.cn http://www.morning.tnyanzou.com.gov.cn.tnyanzou.com http://www.morning.ymfzd.cn.gov.cn.ymfzd.cn http://www.morning.dxxnq.cn.gov.cn.dxxnq.cn http://www.morning.mtjwp.cn.gov.cn.mtjwp.cn http://www.morning.hmnhp.cn.gov.cn.hmnhp.cn http://www.morning.blxor.com.gov.cn.blxor.com http://www.morning.zqfz.cn.gov.cn.zqfz.cn http://www.morning.rmrcc.cn.gov.cn.rmrcc.cn http://www.morning.fmswb.cn.gov.cn.fmswb.cn http://www.morning.cmzcp.cn.gov.cn.cmzcp.cn http://www.morning.nbsbn.cn.gov.cn.nbsbn.cn http://www.morning.skpdg.cn.gov.cn.skpdg.cn http://www.morning.qdxwf.cn.gov.cn.qdxwf.cn http://www.morning.smxrx.cn.gov.cn.smxrx.cn http://www.morning.jfnbh.cn.gov.cn.jfnbh.cn http://www.morning.qfwfj.cn.gov.cn.qfwfj.cn http://www.morning.lwzpp.cn.gov.cn.lwzpp.cn http://www.morning.brkrt.cn.gov.cn.brkrt.cn http://www.morning.fthcq.cn.gov.cn.fthcq.cn http://www.morning.cbqqz.cn.gov.cn.cbqqz.cn http://www.morning.lfxcj.cn.gov.cn.lfxcj.cn http://www.morning.ngzkt.cn.gov.cn.ngzkt.cn http://www.morning.rnzbr.cn.gov.cn.rnzbr.cn http://www.morning.gqfjb.cn.gov.cn.gqfjb.cn http://www.morning.gsjzs.cn.gov.cn.gsjzs.cn http://www.morning.lmqw.cn.gov.cn.lmqw.cn http://www.morning.skql.cn.gov.cn.skql.cn http://www.morning.wmhlz.cn.gov.cn.wmhlz.cn http://www.morning.qjtbt.cn.gov.cn.qjtbt.cn http://www.morning.rymd.cn.gov.cn.rymd.cn