Python 中的继承在规范上与其他语言相同吗?一个与 Java 的对比示例 [英] Is Inheritance in Python canonically the same as in other languages? A comparative example with Java

查看:67
本文介绍了Python 中的继承在规范上与其他语言相同吗?一个与 Java 的对比示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been puzzling today, as (simplified) python code seemed to raise an exception.

这是python中的代码:

Here's the code in 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())

返回:使用test"调用的子项.

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

It means the code is trying to use the child class's get_data within the AwinBaseOperator constructor, which should be wrong. So I tried to confirm this behavior isn't normal by translating my code to Java and running it.

这是相关的Java代码:

Here is the relevant Java code :

我创建了一个项目,其结构是这样的.

I create a project, which is structured as such.

--- 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 用 test 调用 getData.

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

推荐答案

Java 中的示例没有显示 Overriding 的使用,而是 的使用重载 getData 方法.

The shown example in Java does not display the use of Overriding, but that of Overloading the getData method.

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

Once we change the signature of AwinTransactionOperator.getData to

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

输出是Child调用getData with test.

Python 不支持重载.

Python does not support overloading.

这篇关于Python 中的继承在规范上与其他语言相同吗?一个与 Java 的对比示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆