Here is the code I was trying to write:
class A(object):
def bind_foo(self):
old_foo = self.foo
def new_foo():
old_foo()
#super().foo()
super(self.__class__,self).foo()
self.foo = new_foo
def __init__(self):
print("A __init__")
def foo(self):
print("A foo")
class B(A):
def __init__(self):
print("B __init__")
super().__init__()
def foo(self):
print("B foo")
super().foo()
class C(A):
def __init__(self):
print("C __init__")
super().__init__()
super().bind_foo()
def foo(self):
print("C foo")
b = B()
b.foo()
c = C()
c.foo()
Class B and A is the expected behavior, that is, when I call b.foo()
, it calls a.foo()
as well with super()
. Class C is the trying to mimic the child B and parent A behavior but this time I dont want to put explicitly super().foo()
in the child class but I still want the parent foo()
to be called. It works as expected.
However, what I dont quite get is that, under A.bind_foo
, I have to use super(self.__class__,self).foo()
rather than super().foo
. super().foo
gives a
"SystemError: super(): no arguments".
Can someone explain why that is so?
bind_foo
is wrong.super(self.__class__, self).foo()
is actually callingfoo
on the first superclass of the actual instance. So, if you hadclass B(A)
, thenclass C(B)
, thenclass D(C)
, and didD().bind_foo()
, you'd end up calling theC
implementation. That can't what you want. If you want to call theD
implementation, just callself.foo()
. If you want to call theA
implementation, callA.foo(self)
.D
to call its own implementation, thenC
thenB
thenA
.