Why aren't python nested functions called closures?

后端 未结 8 873
情歌与酒
情歌与酒 2020-11-22 05:37

I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called nested functions instead of closures<

8条回答
  •  佛祖请我去吃肉
    2020-11-22 06:13

    I'd like to offer another simple comparison between python and JS example, if this helps make things clearer.

    JS:

    function make () {
      var cl = 1;
      function gett () {
        console.log(cl);
      }
      function sett (val) {
        cl = val;
      }
      return [gett, sett]
    }
    

    and executing:

    a = make(); g = a[0]; s = a[1];
    s(2); g(); // 2
    s(3); g(); // 3
    

    Python:

    def make (): 
      cl = 1
      def gett ():
        print(cl);
      def sett (val):
        cl = val
      return gett, sett
    

    and executing:

    g, s = make()
    g() #1
    s(2); g() #1
    s(3); g() #1
    

    Reason: As many others said above, in python, if there is an assignment in the inner scope to a variable with the same name, a new reference in the inner scope is created. Not so with JS, unless you explicitly declare one with the var keyword.

提交回复
热议问题