python中变量作用域规则以及闭包

1. 变量作用域规则

Python在编译函数的定义体时,如果某个函数体外的变量在定义体中被赋值了,会判断它是局部变量。
要想在函数赋值后仍将其解释成全局变量,需要使用global声明。

  b = 6
  def f3(a):
    global b # 未用global声明之前b被解释为局部变量
    print(a)
    print(b)
    b = 9

2. 闭包

什么是闭包?

闭包也是一种函数,能够保留在函数体中出现的自由变量的绑定。

自由变量:未在本地作用域中绑定的变量

闭包的作用举例

  def make_averager():
    series = []
    
    def averager(new_value):
      series.append(new_value)
      total = sum(series)
      return total / len(series)
    
    return averager

  说明:series由于是averager函数体外绑定的变量,它会保存在函数对象的__code__属性中
  如果自由变量是不可变对象,情况就变了。
  def make_averager():
    count = 0
    total = 0
    
    def averager(new_value):
      count += 1
      total += new_value
      return total / count
    
    return averager

  说明:count和total在averager函数中被重新赋值,相当于隐式的创建了局部变量count和total,这样,count和total就不再自由变量了,函数执行会报错。为了解决这个问题,要加上nonlocal声明,将变量标记为自由变量。
posted @ 2022-05-03 15:29  SmartLiu  阅读(63)  评论(0编辑  收藏  举报