如果未调用父构造函数(与Java不同),多态性在Python中如何工作? - java

因此,父类构造函数是在Java中调用的,而在Python中则不是。如果这意味着未创建父对象,那么如何在Python中成功调用def function-这是怎么回事?

Python代码

class Parent:
    def __new__(self):
        print(f"I am the real parent constructor Hahahah {self}")
        return object.__new__(self)

    def __init__(self):
        print(f"I am the constructor of parent {self}")

    def function(self):
        print(f"I am parent's member function and my self value is {self}")

    def over(self):
        print(f"I am parent's O-function and my self value is {self}")

class Child(Parent):
    def __new__(self):
        print(f"I am the real chid constructor Hahahah {self}")
        return object.__new__(self)

    def __init__(self):
        print(f"I am the initialize of child {self}")

    def over(self):
        print(f"I am the child's member O-function and my self value is {self}")

ch = Child()
ch.over()
ch.function()

以上Python代码的输出。
注意:没有打印I am the real parent constructor Hahahah

I am the real chid constructor Hahahah <class '__main__.Child'>
I am the initialize of child <__main__.Child object at 0x7f4bb5d997b8>
I am the child's member O-function and my self value is <__main__.Child object at 0x7f4bb5d997b8>
I am parent's member function and my self value is <__main__.Child object at 0x7f4bb5d997b8>

类似的Java代码

public class main {

    public static void main(String[] args) {
        Child ch = new Child();
        ch.over();
        ch.function();
    }
}

class Parent {
    Parent () {
        System.out.println("In the parent class constructor | " + this);
    }

    public void function () {
        System.out.println("In the member function of parent | " + this);
    }

    public void over () {
        System.out.println("In the member O-function of parent | " + this);
    }
}

class Child extends Parent {
    Child () {
        System.out.println("I the child class constructor | " + this);
    }

    public void over () {
        System.out.println("In the member O-function of chlid | " + this);
    }
}

上面的Java代码的输出

In the parent class constructor | code.Child@2a139a55
I the child class constructor | code.Child@2a139a55
In the member O-function of chlid | code.Child@2a139a55
In the member function of parent | code.Child@2a139a55

参考方案

Python和Java不同。

在Java 中,扩展类必须始终调用父构造函数。为了使生活更轻松,如果父构造函数没有参数,则会首先自动调用它。现在,如果要像这样向Java Parent构造函数添加一个参数:

Parent (int i) {
    System.out.println("In the parent class constructor | " + this);
}

您会发现以下编译错误:

There is no default constructor available in 'org.example.Parent'

这很有意义,当构造Child Java时不知道作为值i传递什么。因此,我们必须手动调用Parent构造函数:

Child () {
    super(1);
    System.out.println("I the child class constructor | " + this);
}

Python的不太严格。始终调用父构造函数仍然是一个好习惯,但是Python不需要您这样做。这是因为Python不是type safe。

现在让我们看看如果忘记调用父构造函数会发生什么:

class Parent:
    def __init__(self):
        self.i = 1
        print(f"I am the constructor of parent {self}")

    def printi(self):
        print(self.i)

class Child(Parent):

    def __init__(self):
        pass

ch = Child()
ch.printi()

将会发生致命错误:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    ch.printi()
  File "test.py", line 7, in printi
    print(self.i)
AttributeError: 'Child' object has no attribute 'i'

要修复此代码,您可以将以下行添加到Child init 函数:

Parent.__init__(self)

如您所见,仍然创建了Parent类(因为您可以调用function方法。这再次是因为Python不太严格。In python an object can be created without calling the constructor.

Java-父类正在从子类中调用方法? - java

抱歉,我还是编码的新手,可能还没有掌握所有术语。希望您仍然能理解我的问题。我想得到的输出是:"Cost for Parent is: 77.77" "Cost for Child is: 33.33" 但是,我得到这个:"Cost for Parent is: 33.33" "Cost f…

Java-搜索字符串数组中的字符串 - java

在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…

Java Scanner读取文件的奇怪行为 - java

因此,在使用Scanner类从文件读取内容时,我遇到了一个有趣的问题。基本上,我试图从目录中读取解析应用程序生成的多个输出文件,以计算一些准确性指标。基本上,我的代码只是遍历目录中的每个文件,并使用扫描仪将其打开以处理内容。无论出于何种原因,扫描程序都不会读取其中的一些文件(所有UTF-8编码)。即使文件不是空的,scanner.hasNextLine()在…

Java Globbing模式以匹配目录和文件 - java

我正在使用递归函数遍历根目录下的文件。我只想提取*.txt文件,但不想排除目录。现在,我的代码如下所示:val stream = Files.newDirectoryStream(head, "*.txt") 但是这样做将不会匹配任何目录,并且返回的iterator()是False。我使用的是Mac,所以我不想包含的噪音文件是.DS_ST…

直接读取Zip文件中的文件-Java - java

我的情况是我有一个包含一些文件(txt,png,...)的zip文件,我想直接按它们的名称读取它,我已经测试了以下代码,但没有结果(NullPointerExcepion):InputStream in = Main.class.getResourceAsStream("/resouces/zipfile/test.txt"); Buff…