3

I have a file test.py

class A(B):
  def display(self):
      print ("In A")

class B:
  def display(self):
    print ("In B")

I get the following error while run it Traceback (most recent call last):

File "/Users/praveen/Documents/test.py", line 1, in <module>
   class A(B):
NameError: name 'B' is not defined

But if I change the order of declaration, It runs without any errors

class B:
  def display(self):
    print ("In B")

class A(B):
  def display(self):
      print ("In A")

Can anyone explain in detail why this weird error happens?

1
  • 5
    Because Python won't know what B means until you've defined it. It's not really that weird. Commented Jan 24, 2018 at 9:54

2 Answers 2

3

This happens because python gets interpreted Top-To-Bottom. In the line where you define class A(B) in your first example, class B was not yet read by python.

In your second example, B is already known in the line class A(B). That's why it runs.

Sign up to request clarification or add additional context in comments.

Comments

2

simple: when python evaluates class A(B): B is still undefined,

unfortunately python has no class prototypes (or forward declarations)

but this is only a problem if you have 2 classes that explicitly need to point to each other.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.