来自导入类的 UnboundLocalError
我有一些结构如下的代码
from my.modules import MyClass
Class AnotherClass(object):
def __init__(a): #line 5
if a:
setup_a()
else:
setup_b()
def setup_a():
# Do some stuff to get local_x
# ..
self.a = MyClass(local_x)
def setup_b():
# Do some stuff to get local_y
# ..
self.b = MyClass(local_y)
但是我在第 5 行使用 a = True
运行,它运行良好,但是当我使用 a = False
运行时,我得到一个 无界本地错误
。我了解通常导致此问题的原因(修改全局变量),如果我将 setup_b() 更改为:
def setup_b():
global MyClass
# Do some stuff to get local_y
# ..
self.b = MyClass(local_y)
它可以正常工作。我只是不明白为什么会收到此错误,因为我没有通过实例化 MyClass 来修改它。
注意:上面的示例是代码的基本版本,而不是产生错误的实际代码。 有谁知道是什么导致了这个错误?
I have some code that is structured as follows
from my.modules import MyClass
Class AnotherClass(object):
def __init__(a): #line 5
if a:
setup_a()
else:
setup_b()
def setup_a():
# Do some stuff to get local_x
# ..
self.a = MyClass(local_x)
def setup_b():
# Do some stuff to get local_y
# ..
self.b = MyClass(local_y)
However I run with a = True
in line 5 it runs fine, but when I run with a = False
I get an UnboundedLocalError
. I understand what causes this normally (modifying a global variable) and if I change setup_b() to:
def setup_b():
global MyClass
# Do some stuff to get local_y
# ..
self.b = MyClass(local_y)
It works correctly. I just don't understand why I am getting this error as I am not modifying the MyClass by instantiating it.
Note: The above example is a basic version of the code not the actual code producing the error.
Does anyone know what is causing this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在代码中的某个位置,您没有显示您正在分配给
MyClass
,使编译器认为它是局部变量,但实际上它不是。Somewhere in the code you're not showing you're assigning to
MyClass
, making the compiler think that it's a local variable when it's not.