动态更改闭包中调用的方法

时间:2018-09-13 20:49:58

标签: python functional-programming

我正在尝试解决一个棘手的问题,我不知道如何以一种优雅的方式在python中解决问题。

假设我有一个添加了函数的类:

class A(object):
    def __init__(self, fn):
        self.fn = fn #assuming fn is from int to int

比方说,我也在创建一个包装器:

class A_twice(object):
    def __init__(self, a_instance):
        def do_twice(x):
            return a_instance.fn(x) + a_instance.fn(x)
        self.fn = do_twice

假设我正在围绕A创建第二个包装器:

class A_with_storage(object):
    def __init__(self, a_instance):
        def fn_store_output(x, list_):
            value = a_instance.fn(x)
            list_.append(value)
            return value
        self.fn_with_storage = fn_store_output

我可以执行以下操作:

a = A(lambda x : x*x)
a.fn(3) #9
a_twice = A_twice(a)
a_twice.fn(3) #18
a_stored = A_with_storage(a)
l = []
a_stored.fn_with_storage(3, l)
#l = [9]
a_twice_stored = A_with_storage(a_twice)
l2 = []
a_twice_stored.fn_with_storage(3,l2)
#l2 = [18]

我们可以看到,fn_with_storage将调用包装到fn,但没有将“内部”调用包装到由初始fn完成的内部fn。有没有办法做到这一点? 我想要的是一种“神奇”的方式来定义A_with_storage,例如:

a_twice_stored = A_with_storage(a_twice)
l2 = []
a_twice_stored.fn_with_storage(3,l2)
#l2 = [9,9,18]

即“存储”包装将自动应用于在每个闭包内对“ fn”进行的所有调用。这样的事情有可能吗?如果可能的话,我可以用装饰器或其他东西“标记”每个fn函数

谢谢!

0 个答案:

没有答案