Feb-01-2024, 07:21 AM
hi in code:
now we are in the class child1 and for the mro of this class, the form1 method of parent class must be called. but the form1 method of class child2 is called.
explain to me why Python acts as this.
As in the docstring of this code has been written, this subject has been discussed in the given address, but the issue is ambiguous to me still.
thanks
''' from:https://stackoverflow.com/questions/64740117/how-method-resolution-order-mro-is-working-in-this-python-code title of the above page: How Method Resolution Order (MRO) is working in this Python code ''' class parent: def __init__(self): self.a=2 self.b=4 def form1(self): print("calling parent from1") print('p',self.a+self.b) class child1(parent): def __init__(self): self.a=50 self.b=4 def form1(self): print('bye',self.a-self.b) def callchildform1(self): print("calling parent from child1") super().form1() class child2(parent): def __init__(self): self.a=3 self.b=4 def form1(self): print('hi',self.a*self.b) def callchildform1(self): print("calling parent from child2") super().form1() class grandchild(child1,child2): def __init__(self): self.a=10 self.b=4 def callingparent(self): super().form1() print(f" grandchild.__mro__ is {grandchild.__mro__}") g=grandchild() g.callchildform1() print(f"child1.__mro__ is {child1.__mro__}")the output is:
Output: grandchild.__mro__ is (<class '__main__.grandchild'>, <class '__main__.child1'>, <class '__main__.child2'>, <class '__main__.parent'>, <class 'object'>)
calling parent from child1
hi 40
child1.__mro__ is (<class '__main__.child1'>, <class '__main__.parent'>, <class 'object'>)
according to MRO of the class grandchild, the line g.callchildform1() causes to callchildform1's method in classchild1 class is called and in this method there is super().form1() (line 22).now we are in the class child1 and for the mro of this class, the form1 method of parent class must be called. but the form1 method of class child2 is called.
explain to me why Python acts as this.
As in the docstring of this code has been written, this subject has been discussed in the given address, but the issue is ambiguous to me still.
thanks