2017-07-28 14 views
0

j'ai écrit un exemple simple de ce que im essayant de faire:d'application de la réduction de la bêta (appel func qui retourne func) pour obtenir une abstraction (fonction) en 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

Je me attendais deuxième ligne pour imprimer 6 (comme 3 * 2), comment le faire correctement?

Répondre

0

bien c'était plus facile alors je pensais :

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) 

cela fonctionne

0

vous évaluez le lambda function; au contraire, vous devez return il:

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

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

qui donne:

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

une autre façon de faire est d'utiliser 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) fonctionne comme prévu, son Test.FUNC2 qui ne marche pas de travail ... cette réponse est hors de propos ... –

+0

@OfekRon oh, je mislabeled la fonction dans les deux exemples. fixé maintenant ... vous n'avez eu aucun problème avec 'FUNC1', n'est-ce pas? –