应用测试还原(调用FUNC返回FUNC),以获得在python的抽象(功能)

问题描述:

我写的什么我尝试做一个简单的例子:应用测试还原(调用FUNC返回FUNC),以获得在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),如何做到这一点?

清楚,是比较容易的话,我想:

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) 

这个作品

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

Test.FUNC1(2)正常工作,其Test.FUNC2是行不通......这个答案是不相关的... –

+0

@OfekRon哦,我在这两个例子贴错标签的功能。现在修好了......你对FUNC1没有任何问题,对吧? –