Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class inheritance order

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?

like image 899
praveen Avatar asked Jun 30 '26 23:06

praveen


1 Answers

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.

like image 125
FERNman Avatar answered Jul 03 '26 14:07

FERNman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!