Pythonで、比較関数をパラメーターとして期待する関数に、+
またはパラメーターとしての演算子を渡すにはどうすればよいですか?<
def compare (a,b,f):
return f(a,b)
__gt__()
またはのような関数について読んだことがあります__lt__()
が、それでも使用できませんでした。
Pythonで、比較関数をパラメーターとして期待する関数に、+
またはパラメーターとしての演算子を渡すにはどうすればよいですか?<
def compare (a,b,f):
return f(a,b)
__gt__()
またはのような関数について読んだことがあります__lt__()
が、それでも使用できませんでした。
import operator
def compare(a,b,func):
mappings = {'>': operator.lt, '>=': operator.le,
'==': operator.eq} # and etc.
return mappingsp[func](a,b)
compare(3,4,'>')
メソッドパラメーターとしてラムダ条件を使用します。
>>> 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
>>>