2012-11-09 52 views
6

在Python中,如何將像+<這樣的運算符作爲參數傳遞給需要比較函數作爲參數的函數?運算符python參數

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

我看了一下功能,如__gt__()__lt__()但我仍然無法使用。

回答

11

operator module是你在找什麼。 在那裏您可以找到與常用操作員相對應的功能。

例如

operator.lt 
operator.le 
+0

這工作。謝謝。 – 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

爲什麼'lambda'?你不只是想'''':operator.lt,'> =':operator.le,...}' – mgilson

+0

只是忘記檢查沒有+1的評論 –

0

使用lambda條件作爲方法參數:

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