Is Inheritance in Python canonically the same as in other languages? A comparative example with Java

好久不见. 提交于 2021-01-29 09:47:54

问题


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

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())

This returns: Child called with 'test.'

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.

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

Here are the respective class definitions

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");
    }
}

Which returns Parent called getData with test.

  1. Could you please explain this fundamental difference in processing the main Object Oriented concept 'inheritance'?
  2. What am I missing?

回答1:


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

Once we change the signature of AwinTransactionOperator.getData to

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

The output is Child called getData with test.

Python does not support overloading.



来源:https://stackoverflow.com/questions/65723560/is-inheritance-in-python-canonically-the-same-as-in-other-languages-a-comparati

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!