“分配前引用的局部变量"——只有功能? [英] "local variable referenced before assignment" — only functions?

查看:28
本文介绍了“分配前引用的局部变量"——只有功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入以下代码:

import something

def Foo():
    something = something.SomeClass()
    return something

...这显然不是有效代码:

…this is apparently not valid code:

UnboundLocalError: local variable 'something' referenced before assignment

...因为在评估 = 的 RHS 之前,局部变量 something 已创建,但未分配.(例如,请参阅此相关答案的评论.)这对我来说似乎有点奇怪,但可以肯定,我会同意的.现在,为什么下面的代码是有效的?

…as the local variable something is created, but not assigned, before the RHS of the = is evaluated. (See, for example, this related answer's comment.) This seems a bit odd to me, but sure, I'll go with it. Now, why is the following valid code?

class Foo(object):
    something = something.SomeClass()

我的理解是 class 定义的内部本质上是一个作用域:

My understanding was that the inside of a class definition was essentially a scope:

然后在新的执行框架中执行类的套件(参见命名和绑定部分),使用新创建的本地命名空间和原始全局命名空间.

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.

那么,为什么该代码的行为与函数的行为不同?

So, then, why does that code act differently than that of a function?

推荐答案

来自 python 类文档:

类定义在本地作用域中放置了另一个命名空间.

Class definitions place yet another namespace in the local scope.

Python 的一个特殊之处在于——如果没有全局语句生效——对名称的赋值总是进入最内部的作用域.赋值不会复制数据——它们只是将名称绑定到对象.删除也是如此:语句 del x 从本地作用域引用的命名空间中删除 x 的绑定.实际上,所有引入新名称的操作都使用局部作用域:特别是,import 语句和函数定义将模块或函数名称绑定在局部作用域中.(全局语句可用于指示特定变量位于全局范围内.)

A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects. The same is true for deletions: the statement del x removes the binding of x from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope. (The global statement can be used to indicate that particular variables live in the global scope.)

因此,在函数(或作用域)中,赋值会创建一个局部未绑定变量,该变量在绑定之前会被访问,而在类定义中,它会在命名空间"中创建一个条目.分配时该类的字典,允许将 something 解析到外部命名空间(模块命名空间).

So within a function (or a scope) the assignment creates a local unbound variable that is accessed before it is bound, whereas in a class definition it creates an entry in the "namespace" dictionary of that class on assignment, allowing the resolution of something to the outer namespace (the module namespace).

这篇关于“分配前引用的局部变量"——只有功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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