I would like to override the method of an instance of class A with a method from class B but in a way so that all references to the old method of the instance (made before overriding the method) then 'link' to the new one. In code:
import types
class A:
def foo(self):
print('A')
class B:
def foo(self):
print('B')
class C:
def __init__(self, a):
self.func = a.foo
def do_something(self):
self.func()
a = A()
c = C(a)
method_name = 'foo' # it has to be dynamic
new_method = getattr(B, method_name)
setattr(a, method_name, types.MethodType(new_method, a))
c.do_something() # still prints A, I want it to print B now
I want c.func
to hold the new method from class B after the attribute of a has been set (without doing anything with the c object).
Is there a way to set the attribute of the instance a so that all previously made references then refer to the new method?
Sorry if this question is kind of stupid, I am not that much into this.
c
must knowa
, not justa.foo
. Is that an acceptable change from your setup? – MisterMiyagi