在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,'>')
将 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
>>>
lambda
?难道你不只是想要{'>':operator.lt, '>=':operator.le, ... }
吗? - mgilson