简体   繁体   English

python类继承顺序

[英]python class inheritance order

I have a file test.py 我有一个文件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): 运行它时会收到以下错误:Traceback(最近一次调用最后一次):

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. 这是因为python被解释为Top-To-Bottom。 In the line where you define class A(B) in your first example, class B was not yet read by python. 在第一个示例中定义class A(B)中, class B尚未被python读取。

In your second example, B is already known in the line class A(B) . 在第二个示例中, B已在行class A(B)已知。 That's why it runs. 这就是它运行的原因。

simple: when python evaluates class A(B): B is still undefined, simple:当python评估class A(B): B仍未定义,

unfortunately python has no class prototypes (or forward declarations) 不幸的是,python没有类原型(或前向声明)

but this is only a problem if you have 2 classes that explicitly need to point to each other. 但如果您有2个明确需要指向彼此的类,这只是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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