Python nonlocal statement

前端 未结 9 1202
我在风中等你
我在风中等你 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:26

    @ooboo:

    It takes the one "closest" to the point of reference in the source code. This is called "Lexical Scoping" and is standard for >40 years now.

    Python's class members are really in a dictionary called __dict__ and will never be reached by lexical scoping.

    If you don't specify nonlocal but do x = 7, it will create a new local variable "x". If you do specify nonlocal, it will find the "closest" "x" and assign to that. If you specify nonlocal and there is no "x", it will give you an error message.

    The keyword global has always seemed strange to me since it will happily ignore all the other "x" except for the outermost one. Weird.

提交回复
热议问题