【问题标题】:Is Inheritance in Python canonically the same as in other languages? A comparative example with JavaPython 中的继承规范与其他语言中的继承相同吗?与 Java 的比较示例
【发布时间】:2021-01-14 17:06:29
【问题描述】:

我今天一直很困惑,因为(简化的)python 代码似乎引发了异常。

这是python中的代码:

class AwinBaseOperator:
    def __init__(self):
        self.data = self.get_data(query_url='test')

    def get_data(self, query_url):
        print('Parent called with ', repr(query_url))

class AwinTransactionOperator(AwinBaseOperator):
    def __init__(self):
        super().__init__()

    def get_data(self):
        print('Child called')
        
print(AwinTransactionOperator())

这会返回:Child called with 'test.'

这意味着代码试图在AwinBaseOperator构造函数中使用子类的get_data,这应该是错误的。所以我试图通过将我的代码翻译成 Java 并运行它来确认这种行为是不正常的。

这里是相关的Java代码:

我创建了一个项目,它的结构是这样的。

--- Project
 |---src
   |---Main.java  // Contains the main function call
   |---Awin
     |---AwinBaseOperator.java
     |---AwinTransactionOperator.java

这是各自的类定义

import Awin.AwinTransactionOperator;


public class Main {
  public static void main(String[] args) {
    AwinTransactionOperator a = new AwinTransactionOperator();
  }
}
package Awin;


public class AwinBaseOperator{
        
     public AwinBaseOperator(){
         this.getData("test");
     }
     
     public void getData(String query_url){
         System.out.println("Parent called getData with "+query_url);
     }
}
package Awin;
import Awin.AwinBaseOperator;


public class AwinTransactionOperator extends AwinBaseOperator{
    
    public AwinTransactionOperator(){
        super();
    }
    
    public void getData(){
        System.out.println("Child called getData");
    }
}

返回Parent called getData with test.

  1. 您能否解释一下在处理面向对象的主要概念“继承”时的这一根本区别?
  2. 我错过了什么?

【问题讨论】:

  • 我认为在python 中,类在调用__init__() 之前确定了所有方法。总的来说,我不认为method resolution during construction是由继承的概念定义的。
  • 您的测试无效,因为AwinTransactionOperator.getData 不会覆盖AwinBaseOperator 中的方法 - 它会重载它。 (它有不同的参数。)此外,它仍然写“Parent called getData”,而应该写“Child called getData”。
  • 但是一旦它确实覆盖了该方法,您将看到调用了AwinTransactionOperator 实现,而不是AwinBaseOperator 实现。
  • 作为旁注,这个问题的标题毫无意义地具有挑衅性。即使 Python 和 Java 在这里表现不同,推测这会使 Python 继承“中断”也无济于事。
  • 好的,你的所有评论都记录下来了。事实上,当我给函数提供相同的签名时,Child class 方法就会被调用。感谢您消除误解。

标签: java python oop inheritance


【解决方案1】:

Java 中的示例没有显示Overriding 的使用,而是Overloading getData 方法的使用。

一旦我们将AwinTransactionOperator.getData的签名更改为

public void getData(String query_url){
        System.out.println("Child called getData with "+query_url);
}

输出为Child called getData with test

Python 不支持重载

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2015-07-04
    相关资源
    最近更新 更多