闭包-和-nonlocal

闭包

python 中在一个函数内有一个新定义的函数,称为闭包

nonlocal

这里介绍在闭包中怎么使用 nonlocal 使用场景:leetcode 代码中常定义函数,而不是定义一个 self 的类函数,此时经常会遇到变量的作用域问题。

总结如下:

  1. 在内部函数前定义的可变对象(list, dict),是可以直接在内部函数里使用的,并且一经修改,内外全变
    def outside():
        d = {"outside": 1}
        def inside():
            d["inside"] = 2
            print(d)
        inside()
        print(d)
        
    >>>
    {'outside': 1, 'inside': 2} # 可变变量,不用nonlocal,一变全变
    {'outside': 1, 'inside': 2}
  2. 在内部函数前定义的不可变对象(int, string, float, tuple),无法直接使用,需要使用 nonlocal 指定后才能直接使用。
    def outside():
      msg = "Outside!"
      def inside():
          msg = "Inside!" # 没有这句直接下一句会报错
          print(msg)
      inside()
      print(msg)
     
    >>> # 不可变变量,内部需要申明nonlocal
    Inside!
    Outside!