+ 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()
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"
+ 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()
+ 3
C.__mro__[-2]().spam()
# will print 1
+ 3
thank Vitaly Sokol.
mro is not widely known, but it's the better answer.
+ 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 ?
+ 1
Bob_Li Thanks for the geeks for geeks page buddy. That topic sure feels interesting.
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