什么时候用Python创建符号表

2024-05-23 20:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

def square():
    print(a)
    a = 10
    b = a*a
    return b

a = 2

print(square())

UnboundLocalError:赋值之前引用了局部变量“a”

^{pr2}$

我只想弄清楚为什么第二种情况是正确的,而第一种情况是错误的。在

The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names.

当解释器完成函数的定义时,它会创建一个符号表。它首先认为“a”是全局的(由于打印(a)),然后在本地符号表中创建“a”(由于赋值)。在

因此,在实际执行函数时,“a”是一个没有绑定的局部函数。因此出现了错误。在

我对符号表的推理正确吗??在

更新:在分配后添加全局:

def square():
    print(a)
    a = 10
    b = a*a
    global a
    return b

a = 2

print(square())

print(a)

global a语句是否从square函数的本地符号表中删除名称'a'?在


Tags: ofthe函数inreturnlocaldeftable
1条回答
网友
1楼 · 发布于 2024-05-23 20:15:04

这是一个范围问题。检查这个答案:https://stackoverflow.com/a/293097/1741450

Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope.

第一个例子是错误的,因为a不能被修改。在

相关问题 更多 >