将方法从实例中解除绑定并绑定到其他实例



我已经读过了。是否可以更改:a1.showa2.show,我的意思是,更改方法的方向以指向不同的实例。

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)

我想在控制台中看到2。我的意思是,对于类中的普通方法,将其实例从a1更改为a2


你可能想知道我为什么这么做,我有一个装饰器来记录实例所经历的一切。

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

现在,我可以将这个装饰器添加到每次调用都需要记录的函数中。例如,我希望linear录制,但要换行。

class Data:
def wrap(self):
print('wrap')
@record
def linear(self, least_square=True):
pass

现在,我可以定义一个simulate函数,它在另一个实例中传递,并让它经历这个实例所经历的一切。

但是,我的缓存只记录了foo.__name__,我需要编写自己的映射程序来决定调用哪个函数。这很复杂。因此,我不想记录foo.__name__,而是想直接记录foo,并将其方向从自身改变为他人。

希望我解释得足够清楚。如果你帮我一把,我会很高兴的。

我刚刚注意到python对象的方法没有绑定到实例,如果我将foo存储在record中,我需要传入self作为第一个参数。

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

这是可行的。

最新更新