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

时间:2021-05-06 15:18:15

标签: python class bind

我已阅读this。是否可以将:a1.show 更改为 a2.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,并将其方向从self 更改为other。

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

1 个答案:

答案 0 :(得分:0)

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

这行得通。