python的闭包
首先python闭包的作用,一个是自带作用域,另一个是延迟计算。
闭包是装饰器的基础。
闭包的基本形式:
——————————————————————————
def 外部函数名():
内部函数需要的变量
def 内部函数名()
引用外部的变量
return 内部函数
——————————————————————————
需要注意的是:
函数的作用域关系在函数定义阶段就已经固定,与调用位置无关。
无论函数在何处调用,都需要回到定义阶段去找对应的作用域关系。
例子:
def tell_info(name): print("%s have money %s" %(name,money)) def foo(): money = 100 tell_info("bill") foo()
该代码tell_info("bill")是在foo函数中调用,但仍然需要回到定义阶段去找作用域关系,而
定义的时候引用的money就是全局的Money,当全局不存在money的时候则报错,抛出未定义错误。
所以该段代码会报错。