【发布时间】:2020-07-24 20:00:41
【问题描述】:
因此,在 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
【问题讨论】:
标签: java python inheritance polymorphism