[英]How can I get around “UnboundLocalError: local variable 'foo' referenced before assignment” errors without global variables?
Here is a simplified version of my code: 这是我的代码的简化版本:
class foo:
def __init__(self, thing):
self.thing = thing
def bar():
foo = foo('test')
bar()
And here's what it produces: 这是它产生的:
Traceback (most recent call last):
File "filepath", line 8, in <module>
bar()
File "filepath", line 6, in bar
foo = foo('test')
UnboundLocalError: local variable 'foo' referenced before assignment
I have a two part question regarding this. 我对此有两个问题。
Firstly, how can I get around this ? 首先, 我该如何解决 ? After some Googling I found that adding a
global foo
before the foo = foo('test')
line does the trick. 经过一番谷歌搜索后,我发现在
foo = foo('test')
行之前添加global foo
可以解决问题。 But the general consensus seems to be that global variables are bad things to be avoided, so is there a way around this that doesn't use global variables? 但是,普遍的共识似乎是全局变量是要避免的坏事情,那么有没有办法避免使用全局变量呢?
And secondly, why is this actually happening? 其次, 为什么这实际上发生了? I understand about functions only being able to access variables created inside that function (and global variables of course).
我了解函数只能访问在该函数内部创建的变量(当然还有全局变量)。 But I'm not trying to access a variable that was defined outside of the function, I'm just creating a new one.
但是我并不是要访问在函数外部定义的变量,而是在创建一个新变量。 Logically speaking, why is it forbidden to create a new object inside a function (unless you declare it as global first)?
从逻辑上讲,为什么禁止在函数内部创建新对象(除非您先将其声明为全局对象)?
As soon as the parser sees foo = ...
, it marks foo
as a local variable. 解析器一看到
foo = ...
,便将foo
标记为局部变量。 Once that happens, your attempt to call foo('test')
fails, because the local variable foo
doesn't refer to anything yet, let alone a callable object. 一旦发生这种情况,您尝试调用
foo('test')
尝试将失败,因为局部变量foo
尚未引用任何东西 ,更不用说可调用对象了。
You're going to have to pick a different name for the object you are creating. 您将不得不为创建的对象选择一个不同的名称。
A variable in Python is always in one scope. Python中的变量始终在一个范围内。
You try to assign to a local variable foo
while reading a global variable foo
. 你试图给一个局部变量
foo
,而读一个全局变量foo
。
When you assign to a variable that isn't declared with the global keyword, it is assumed to be a local variable. 当您分配未使用global关键字声明的变量时,将假定它是局部变量。 So when you write
foo = foo()
Python assumes that foo
is local and then you get the error, that you a reading foo before you wrote to it. 因此,当您编写
foo = foo()
Python假定foo
是本地的,然后您得到错误,即您在写入foo之前先读取了foo。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.