Middle
# 2. Python. Call a class function # Description: # Implement calling the print function of 2 classes: Parent, Child. # With two restrictions: 1 - cannot call Parent class directly by name. 2 - cannot change the behavior of Parent class # You can change the behavior of Child class # Output the result. # Input data: # class Parent: # def __init__(self): # print("Parent") # class Child(Parent): # def __init__(self): # print("Child") # Result: # Parent # Child
sobes.tech AI
Answer from AI
To invoke the constructor of the Parent class without directly calling Parent.init() and without changing the behavior of Parent, you can use the super() function in the Child class.
Example solution:
class Parent:
def __init__(self):
print("Parent")
class Child(Parent):
def __init__(self):
super().__init__() # call the Parent constructor without directly mentioning Parent
print("Child")
child = Child()
The output will be:
Parent
Child
Thus, we do not modify the Parent class and do not call Parent directly, but use super() to invoke the parent constructor.