+ 2

Inheriting a method from two super classes above, how do I do that ?

Suppose I have three classes inheriting each other in a row, each with a method which have common name, How do I access the method from the first class through the third inheriting class ? Here's thecode I tried but it gives errorthat C.super() has no attribute super() class A: def spam(self): print(1) class B(A): def spam(self): print(2) super().spam() class C(B): def spam(self): print("Spam from C") B().spam() (C.super()).super().spam()

17th May 2025, 2:35 PM
Yash Thale
Yash Thale - avatar
9 Respuestas
+ 6
maybe class A: def spam(self): print("Spam from A") class B(A): def spam(self): print("Spam from B") super().spam() class C(B): def spam(self): print("Spam from C") B().spam() #"Spam from B" #"Spam from A" C().spam() #"Spam from C" # syntax for calling super from outside the class: # super(type(instance), instance) super(C,C()).spam() #"Spam from B" #"Spam from A"
17th May 2025, 11:33 PM
Bob_Li
Bob_Li - avatar
+ 4
Vitaly Sokol __mro__ is great. 👍 Yash Thale https://www.geeksforgeeks.org/method-resolution-order-in-JUMP_LINK__&&__python__&&__JUMP_LINK-inheritance/ try this: print(C.mro()) C.mro()[0]().spam() C.mro()[1]().spam() C.mro()[2]().spam()
18th May 2025, 5:53 AM
Bob_Li
Bob_Li - avatar
+ 3
C.__mro__[-2]().spam() # will print 1
17th May 2025, 11:51 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 3
thank Vitaly Sokol. mro is not widely known, but it's the better answer.
18th May 2025, 9:54 AM
Bob_Li
Bob_Li - avatar
+ 1
Vitaly Sokol I'll try it out, meanwhile bro what does .__mro__[-2]() do here ? Like selecting the method from super class of the previous super class ? and this [-2] is the index of how many super classes above the program has to check ? Right ?
18th May 2025, 4:06 AM
Yash Thale
Yash Thale - avatar
+ 1
Bob_Li Thanks for the geeks for geeks page buddy. That topic sure feels interesting.
18th May 2025, 6:07 AM
Yash Thale
Yash Thale - avatar
0
It looks like you're running into an issue with how super() works when you have multiple levels of inheritance in Python. The error "C.super() has no attribute super()" usually means you're trying to call super() in a way that doesn't align with the method resolution order (MRO) of your classes. When you run this code, the output will be: spam from C spam from B spam from A
19th May 2025, 11:48 AM
Kallol Sarker Kabbo
Kallol Sarker Kabbo - avatar