为什么在处理函数和类中的未绑定局部变量方面有所不同? [英] Why the difference in handling unbound locals in functions versus classes?

查看:94
本文介绍了为什么在处理函数和类中的未绑定局部变量方面有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在引用全局变量时,可以看到函数和类对此进行了不同的处理.第一个很好,第二个导致错误:

When referencing global variables, one can see that functions and classes handle this differently. The first is fine and the second causes an error:

x = 10
class Foo():
    x = x + 1
a = foo()

对比:

x = 10
def faa():
    x = x + 1
faa()

Python执行模型中,被描述为:

类定义是可以使用和定义的可执行语句 名称.这些参考遵循名称解析的常规规则 唯一的例外是在 全局名称空间.

A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace.

但是为什么呢?

我遇到的唯一其他提示是此位:

The only other hint I have come across is this bit:

然后在新的执行框架中执行课程的套件(请参见 命名和绑定部分),使用新创建的本地名称空间和 原始的全局名称空间. (通常,套件仅包含 函数定义.)当类的套件完成执行后, 执行帧将被丢弃,但会保存其本地名称空间. 4 A 然后使用基类的继承列表创建类对象 类和属性字典的已保存本地命名空间.

The class’s suite is then executed in a new execution frame (see section Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains only function definitions.) When the class’s suite finishes execution, its execution frame is discarded but its local namespace is saved. 4 A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary.

仍然没有解释为什么这会导致在全局命名空间中查找未绑定的本地变量的原因.

Which still offers no explanation why this should have the consequence that unbound locals are looked up in the global namespace.

两个链接均来自此答案,但没有更详细地说明原因.

Both links are from this answer which does not adress the why in more details though.

推荐答案

Python FAQ-为什么会收到UnboundLocalError?

...,因为当您对作用域中的变量进行赋值时,该变量将成为该作用域的局部变量,并在外部作用域中隐藏任何类似命名的变量.由于foo中的最后一条语句为x分配了一个新值,因此编译器将其识别为局部变量.

因此,当较早尝试访问未初始化的局部变量时,将导致错误.

Consequently when earlier attempting to access the uninitialized local variable an error results.

这解释了为什么这样做:

This explains why this:

x = 10
def foo():
    x = x+1  # raises UnboundLocalError
foo()

引发异常,但不例外:

x = 10
def faa():
    y = x+1  # x stays in global scope, since it is not assigned in local
faa()


对于class foo()来说是相同的,因为python允许在任何给定时间将属性分配给对象.类代码将x分配为对象a的新属性.


For the class foo() it's the same, since python allows assignments of attributes to objects to any given time. The class-code assigns x as new attribute of the object a.

x = 10
class foo():
    x = x+1  # scope of x: class
a = foo()  # x = 10; a.x = foo.x = 11

与以下相同:

x = 10
class foo():
    def __init__(self):
        self.x = x+1  # scope of x: instance
a = foo()  # x = 10; a.x = 11

显然是分配了self.x而不是x,因此也保留在全局范围内. (另请参见此处)

where obviously self.x is assigned instead of x, therefore also staying in global scope. (see also here)

这篇关于为什么在处理函数和类中的未绑定局部变量方面有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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