I have read this. is it possible to change: a1.show
to a2.show
, I mean, change the orientation of the method to point to different instance.
class A:
def __init__(self, a):
self.a = a
def show(self):
print(self.a)
a1 = A(1)
a2 = A(2)
mtd = staticmethod(a1.show)
mtd(a2)
I want to see 2
in console. I mean, for a normal method in class, change its instance, from a1
to a2
?
You may wonder why I do this, I have got a decorator to record what the instance has been through.
class Data:
def __init__(self):
self.caches = []
# do not call it outside of class, it is used to record procedure
def add_cache(self, val):
self.caches.append(val)
def clean_cache(self):
self.caches = []
def record(foo):
def wrapper(self, *args, **kwargs):
self.add_cache({foo.__name__: {'args': args, 'kwargs': kwargs}})
return foo(self, *args, **kwargs)
return wrapper
Now, I can add this decorator to the function that needs to be recorded every call. For example, I want linear
to be recorded but wrap.
class Data:
def wrap(self):
print('wrap')
@record
def linear(self, least_square=True):
pass
Now, I am allowed to define a simulate
function, which pass in another instance, and let it be through what this instance has been through.
But, my cache only recorded foo.__name__
, which I need to write my own mapper to decide which function to call. This is complex. Therefore, instead of recording foo.__name__
, I want to directly record foo
and change its orientation from self to other.
Hope I have explained with enough clarity. I will be so glad if you give me a hand.
I just noticed python object's methods are not bonded to instance, which if I store foo
in record
, I need to pass in self
as first argument.
def simulate(self, other):
for di in self.caches:
kk = list(di.keys())[0]
vv = list(di.values())[0]
kk(other, *vv['args'], **vv['kwargs'])
return self
This works out.