2017-07-28 23 views
0

我寫的什麼我嘗試做一個簡單的例子:應用測試還原(調用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),如何做到這一點?

回答

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) 

這個作品

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 
+0

Test.FUNC1(2)正常工作,其Test.FUNC2是行不通......這個答案是不相關的... –

+0

@OfekRon哦,我在這兩個例子貼錯標籤的功能。現在修好了......你對FUNC1沒有任何問題,對吧? –

相關問題