问题描述
我不太明白为什么代码
def f():
print(s)
s =foo
f()
运行得非常好,但
def f():
print(s)
s =bar
s =foo
f()
给我UnboundLocalError。我知道我可以通过在函数内部声明 s 作为全局变量来解决这个问题,或者只需将 s 作为参数传递给该函数即可解决此问题。
仍然我不明白python是如何知道在该行被执行之前s是否在函数内被引用的?当函数被读入全局框架时,python是否创建了所有局部变量引用的列表?
关注这个实际方面,但实际上并没有回答你问的问题。
是的,Python编译器跟踪编译代码块时分配哪些变量如 def
)。如果在块中分配了名称,编译器会将其标记为本地。请查看函数.__代码__。co_varnames
以查看编译器已识别哪些变量。 p>
nonlocal
和全局
语句可以覆盖它。 p>
I don't quite understand why the code
def f():
print(s)
s = "foo"
f()
runs perfectly fine but
def f():
print(s)
s = "bar"
s = "foo"
f()
gives me UnboundLocalError. I know that I can fix this by declaring s as a global variable inside the function or by simply passing s an an argument into the function.
Still I don't understand how python seemingly knows whether or not s is referenced inside the function before the line has been executed? Does python make some sort of list of all local variable references when the function is read into the global frame?
Other answers have focused on the practical aspects of this but have not actually answered the question you asked.
Yes, the Python compiler tracks which variables are assigned when it is compiling a code block (such as in a def
). If a name is assigned to in a block, the compiler marks it as local.Take a look at function.__code__.co_varnames
to see which variables the compiler has identified.
The nonlocal
and global
statements can override this.
这篇关于本地和全局引用与UnboundLocalError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!