从实例中取消绑定方法并绑定到其他实例

unbind method from instance and bind to other instance

我已阅读this。是否可以更改: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。我的意思是,对于 class 中的普通方法,将其实例从 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

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

class Data:
    def wrap(self):
        print('wrap')

    @record
    def linear(self, least_square=True):
        pass

现在,我可以定义一个simulate函数,它传入另一个实例,让它通过这个实例已经经历过的。

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

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

我刚刚注意到 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

这行得通。