I have two classes in the same file. I am trying to call ClassB from ClassB but receive the following error:
NameError: name 'ClassB' is not defined
class A:
var = B();
class B:
def foo(self):
Class attributes (like A.var that you're trying to define) are evaluated when their class is parsed and created, so B() won't exist when you're trying to reference it in the definition of class A.
Fortunately, you can just add it afterwards and it will have the same effect:
class A:
pass
class B:
def foo(self): pass
A.var = B()
If appropriate, you could also define it as an instance attribute instead:
class A:
def __init__(self):
self.var = B()
class B:
def foo(self): pass
The classes are "seen" in the order in which they are written. Therefore if you have a statement in the first class it will be evaluated directly, on the spot, before going any further in the file.
Your statement var = B() is therefore executed when class B does not exist yet for the Python interpreter.
There are 2 ways to fix this:
var = B() in the constructor of class A as shown belowYour class A will look like this
class A:
def __init__(self):
self.var = B()
This means that the self.var = B will only be evaluated when you create your instance of the class A.
This topic has already been seen several times on Stack Overflow, I would suggest you take a look into one of them in the link below if you have any further questions.
I have made a little program on repl.it to show you as an example if you want. It's here.
Ais defined, at which timeBhasn't yet been defined. DefineBfirst.