UnboundLocalError from imported class
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?
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.
精彩评论