I\'m very new to Python, I figure this question should be easy to answer.
My problem simplified is this...
I have 2 classes in a File class A and class B. Class
class A:
def __init__(self):
print "In A"
class B:
def __init__(self):
a = A()
print "In B"
b = B()
I think you want something like that.
To access B
, you must first have defined B
.
If you want to access B
when you define A
, you need to move it above A
in the file.
If you want to access B
when you call methods in A
, you don't need to do anything: by the time you call a method of A
, the interpreter has executed all the definitions.
When python finds a class declaration it creates a new scope and executes the code inside the class in this code block. This means that all class variables are instantiated when the class declaration is executed.
Now, if you have the two classes like:
class A:
something = B
class B:
pass
Python will execute something = B
before creating the B
class and thus it yields a NameError
.
You can avoid this in a really simple manner:
class A:
something = None
class B:
pass
A.something = B
So the answer was to use qoutes
B = fields.ForeignKey('api.resources.B', 'B')
A workaround that comes to my mind is to separate the classes into multiple files, so you could have a python package "models" in which you'll have A.py and B.py. Then you avoid the ordering issue