1

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):
1
  • 1
    Because that's a class attribute it's created when A is defined, at which time B hasn't yet been defined. Define B first. Commented May 5, 2017 at 22:09

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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:

  1. define the class B before the class A
  2. OR put the statement var = B() in the constructor of class A as shown below

Your 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.

Python class defined in the same file as another class - how do you get access to the one defined later in the file?

I have made a little program on repl.it to show you as an example if you want. It's here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.