2012-11-09 18 views
6

In Python, come posso passare un operatore come + o < come parametro a una funzione che prevede una funzione di confronto come parametro?parametro python operatore

def compare (a,b,f): 
    return f(a,b) 

Ho letto sulle funzioni come __gt__() o __lt__() ma ancora non è stato in grado di usarli.

risposta

11

Il operator module è quello che stai cercando. Trovate funzioni che corrispondono ai soliti operatori.

ad es.

operator.lt 
operator.le 
+0

che ha funzionato. Grazie. – Izabela

5

use operator module for this purposes

import operator 
def compare(a,b,func): 

    mappings = {'>': operator.lt, '>=': operator.le, 
       '==': operator.eq} # and etc. 
    return mappingsp[func](a,b) 

compare(3,4,'>') 
+2

Perché il 'lambda'? Non vuoi semplicemente '{'>': operator.lt, '> =': operator.le, ...}' – mgilson

+0

dimentica semplicemente di controllare senza +1 per il tuo commento –

0

Utilizzare una condizione lambda come un parametro di metodo:

>>> def yourMethod(expected_cond, param1, param2): 
...  if expected_cond(param1, param2): 
...    print 'expected_cond is true' 
...  else: 
...    print 'expected_cond is false' 
... 
>>> condition = lambda op1, op2: (op1 > op2) 
>>> 
>>> yourMethod(condition, 1, 2) 
expected_cond is false 
>>> yourMethod(condition, 3, 2) 
expected_cond is true 
>>>