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'
?在
这是一个范围问题。检查这个答案:https://stackoverflow.com/a/293097/1741450
第一个例子是错误的,因为a不能被修改。在
相关问题 更多 >
编程相关推荐