Python nonlocal statement

前端 未结 9 1266
我在风中等你
我在风中等你 2020-11-22 03:52

What does the Python nonlocal statement do (in Python 3.0 and later)?

There\'s no documentation on the official Python website and help(\"nonloca

9条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 04:30

    A google search for "python nonlocal" turned up the Proposal, PEP 3104, which fully describes the syntax and reasoning behind the statement. in short, it works in exactly the same way as the global statement, except that it is used to refer to variables that are neither global nor local to the function.

    Here's a brief example of what you can do with this. The counter generator can be rewritten to use this so that it looks more like the idioms of languages with closures.

    def make_counter():
        count = 0
        def counter():
            nonlocal count
            count += 1
            return count
        return counter
    

    Obviously, you could write this as a generator, like:

    def counter_generator():
        count = 0
        while True:
            count += 1
            yield count
    

    But while this is perfectly idiomatic python, it seems that the first version would be a bit more obvious for beginners. Properly using generators, by calling the returned function, is a common point of confusion. The first version explicitly returns a function.

提交回复
热议问题