简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM