In Python I have a class Klass(A, B) and another SubKlass(Klass). In SubKlass I want to override a function from Klass, but calling the grand parent function from B. super(B).fn() throws an error?
Assistant
The issue is with your syntax. super(B).fn() is incorrect - you're missing the instance parameter. However, even the corrected syntax won't do what you want in this case.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
class A:
def fn(self):
return "A's method"
class B:
def fn(self):
return "B's method"
class Klass(A, B):
def fn(self):
return "Klass's method"
class SubKlass(Klass):
def fn(self):
# Directly call B's method
return B.fn(self)
Method 2: Understanding MRO with super()
class SubKlass(Klass):
def fn(self):
# This calls the next method in MRO after Klass (which is A.fn)
result = super(Klass, self).fn()
# To get B's method, you'd need to continue down the MRO
# But this is fragile and not recommended
return result
Why super(B, self).fn() doesn't work
When you use super(B, self), it looks for the method in the class that comes after B in the Method Resolution Order (MRO). In your case, the MRO is likely SubKlass -> Klass -> A -> B -> object, so super(B, self).fn() would try to find fn() in object, which doesn't exist.
Best practice
Use the direct class call B.fn(self) when you specifically want to call a particular parent class's method in multiple inheritance scenarios. This is explicit, clear, and reliable.
class SubKlass(Klass):
def fn(self):
b_result = B.fn(self) # Call B's method specifically
# Do additional work
return f"SubKlass extending: {b_result}"