Closures in Python

后端 未结 6 1949
南旧
南旧 2020-12-17 00:42

I\'ve been trying to learn Python, and while I\'m enthusiastic about using closures in Python, I\'ve been having trouble getting some code to work properly:

         


        
6条回答
  •  攒了一身酷
    2020-12-17 01:16

    The problem is in your scoping, not in your closures. If you're up for some heavy reading, then you can try http://www.python.org/dev/peps/pep-3104/.

    If that's not the case, here's the simple explanation:

    The problem is in the statement global get . global refers to the outermost scope, and since there isn't any global function get, it throws.

    What you need, is an access specifier for variables in the enclosing scope, and not the global scope.

    In python 3.0, as I've tested, the nonlocal keyword is exactly what you need, in the place of global.

    nonlocal get
    ...
    

    In python 2.x, I just removed the global get and the oldget references and it works properly.

提交回复
热议问题