我写了一个简单的例子,说明我想做什么:
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),该怎么做呢?
答案 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)
这是有效的