So, parent class constructor is called in Java, but not in Python. If that means that parent object is not created, how is call to def function
in Python successful - What is happening here?
Python code
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()
Output for above Python code.
Note: I am the real parent constructor Hahahah
was not printed.
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>
Similar Java code
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);
}
}
Output for the above Java code
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