本地和全局引用与UnboundLocalError [英] Local and global references with UnboundLocalError

查看:100
本文介绍了本地和全局引用与UnboundLocalError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太明白为什么代码

  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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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