应用 beta-reduction(调用 returns func 的 func)来获得 python 中的抽象(函数)

applying beta-reduction (call func that returns func) to get an abstraction (function) in python

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

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' object is not callable

我希望第二行打印 6(3*2),怎么做对?

您正在评估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

好吧,这比我想的要容易:

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)

这有效