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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With