应用beta-reduction(调用func返回func)来获取python中的抽象(函数)

时间:2017-07-28 15:42:12

标签: python lambda lambda-calculus

我写了一个简单的例子,说明我想做什么:

class Test:
    @staticmethod
    def mul(x,y):
        return x*y
    FUNC1 = staticmethod(lambda y: Test.mul(y,2))
    FUNC2 = staticmethod(lambda y: staticmethod(lambda x: Test.mul(y,x)))
print Test.FUNC1(2)
print Test.FUNC2(2)(3)
print Test.FUNC2(2)(3)
     

TypeError:'staticmethod'对象不可调用

我期待第二行打印6(作为3 * 2),该怎么做呢?

2 个答案:

答案 0 :(得分:0)

您正在评估lambda function;相反,你应该return

class Test:
    @staticmethod
    def mul(x,y):
        return x*y

    @staticmethod
    def FUNC2(y):
        return lambda y: Test.mul(y,2)

给出:

print(Test.FUNC2(2))  # <function Test.FUNC1.<locals>.<lambda> at 0x7f2c92594a60>
print(Test.FUNC2(2)(3))  # 6

另一种方法是使用functools

from operator import mul
from functools import partial

class Test:

    @staticmethod
    def FUNC2(y):
        return partial(mul, y)
    # or
    # FUNC2 = staticmethod(lambda y: partial(mul, y))

print(Test.FUNC2(2))  # functools.partial(<built-in function mul>, 2)
print(Test.FUNC2(2)(3)) # 6

答案 1 :(得分:0)

那么我觉得这更容易:

class Test:
    @staticmethod
    def mul(x,y):
        return x*y
    FUNC1 = staticmethod(lambda y: Test.mul(y,2))
    FUNC2 = staticmethod(lambda y: lambda x: Test.mul(y,x))
print Test.FUNC1(2)
print Test.FUNC2(2)(3)

这是有效的