Python nonlocal statement in a class definition

别说谁变了你拦得住时间么 提交于 2019-11-30 19:16:51

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)

Python handles class and function definitions rather differently. For example, your A.v is not a variable of A but rather an attribute of it. The namespace created by a class is not, therefore, a scope. I am not surprised that nonlocal does not work as you're trying to use it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!