Python nonlocal statement in a class definition

前端 未结 2 1577
走了就别回头了
走了就别回头了 2021-01-04 09:47

I\'m trying to perform some analysis of scope in Python 3 source code and I\'m stuck with how the nonlocal statement statement works inside a class definition.

As I

2条回答
  •  难免孤独
    2021-01-04 10:23

    Lexical scoping applies only to function namespaces, otherwise methods defined inside a class would be able to "see" the class level attributes (which is by design - those attributes must instead be accessed as attributes of self inside the method).

    The same limitations that cause the class level variables to be skipped over by references from methods also keep the nonlocal keyword from working its magic. (global does work though, since that doesn't rely on the lexical scoping machinery)

提交回复
热议问题