Python非局部语句在类定义中 [英] Python nonlocal statement in a class definition

查看:142
本文介绍了Python非局部语句在类定义中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Python 3源代码中执行一些范围分析,并且我坚持非局部语句语句在类定义中如何工作。

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.

根据我的理解,类定义在新的命名空间(称为dict)中执行它的主体,并将类名绑定到类型(name,bases,dict)的结果。非局部x应该工作,只要它引用绑定在封闭的非本地作用域中的某处的变量。

As I understand it, the class definition executes its body inside a new namespace (call it dict) and binds the class name to the result of type(name, bases, dict). Nonlocal x should work as long as it refers to a variable that is bound somewhere in the enclosing non-local scope.

从这我希望下面的代码编译和运行:

From this I expect the following code to compile and run:

class A:
    v = 1
    class B:
        nonlocal v
        v = 2

但这不能通过

SyntaxError: no binding for nonlocal 'v' found

while以下代码完全运行

while the following code runs perfectly

def A():
    v = 1
    class B:
        nonlocal v
        v = 2

任何人都可以解释函数关闭之间的区别定义和类定义?

Can anyone explain the difference here between the closure of the function definition and the class definition?

推荐答案

词法范围仅适用于函数名称空间,否则在类中定义的方法将能够请参阅类级属性(按设计 - 这些属性必须作为属性 self 在方法中访问)。

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).

导致类级别变量被方法引用跳过的同样的限制也使 nonlocal 关键字不起作用。 (全局可以工作,因为这不依赖于词法范围设定机制)

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非局部语句在类定义中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆