python中变量的作用域分为4种,分别是Local、Enclosing、Global和Built-in。Python在解析引用时,按照LEGB的顺序从内向外查找,如果这四个地方都没有定义过名称相符的变量,就抛出NameError异常。
Inner functions, also known as nested functions, are functions that you define inside other functions. In Python, this kind of function has direct access to variables and names defined in the enclosing function. Inner functions have many uses, most notably as closure factories and decorator functions.
在函数A内部定义了函数B,我们称函数B为inner function或者nested function,函数A为enclosing function。
def A():
a = 3
def B():
b = 6
根据变量的作用域,可以将变量分成:
参考资料:Using Enclosing Scopes as Closures
a closure is an inner or nested function that carries information about its enclosing scope, even though this scope has completed its execution.
闭包是带有enclosing scope状态信息的nested function。举个例子来展示闭包的使用:
enclosing function power_factory(exp)相当于一个闭包工厂函数,不同的参数exp会返回不同的power函数。闭包不仅仅是一个函数,它还带有enclosing scope的状态信息。
再写一个不断读取数据计算平均值的例子:
__iter__()
方法和__next__()
方法的对象,其中__iter__()
方法必须返回迭代器本身,__next__()
方法必须返回序列中的下个元素。def index_words(text):
result = []
if text:
result.append(0)
for index, letter in enumerate(text):
if letter == ‘ ‘:
result.append(index + 1)
return result
当text不是非常大时,这样的处理问题不大。当text非常大,比如包括上千万个单词时,程序有可能耗尽内存并崩溃,如果使用生成器改写这个函数,则可以应对任意长度的输入。
def index_words_iter(text):
if text:
yield 0
for index, letter in enumerate(text):
if letter == ‘ ‘:
yield index + 1
定义这种生成器函数时,唯一需要留意的是:函数返回的那个迭代器,是有状态的,调用者不应该反复使用它。
原文:https://www.cnblogs.com/TaipKang/p/15226180.html