Python参数操作符

7

在Python中,我如何将运算符(比如+<)作为参数传递给期望接受比较函数作为参数的函数?

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

我已经了解到像__gt__()或者__lt__()这样的函数,但是我还不能熟练地运用它们。

3个回答

12
operator模块正是你所需要的。在这里,你可以找到对应常规操作符的函数。例如:
operator.lt
operator.le

5

使用operator模块来实现这个目的

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
只是忘记检查你的评论是否有+1。 - Artsiom Rudzenka

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接