Python-在If语句中将字符串用作条件运算符

时间:2018-08-25 03:09:04

标签: python if-statement

在Python中,是否可以在if语句条件下使用字符串作为运算符?

我想有一个带有两个值的对象和一个运算符来测试它们。 例如:

class Condition:
    def __init__(self, value1, operator, value2):
        self.value1 = value1
        self.operator = operator
        self.value2 = value2

    def test(self):
        if self.value1 self.operator self.value2: <- THIS IS NOT CORRECT.
            return True
        else:
            return False

condition = Condition(5, ">", 4)
if condition.test() == True:
    print("passed")
else:
    print("failed")

谢谢。

3 个答案:

答案 0 :(得分:3)

Python的operator模块提供了与所有内置运算符相对应的功能,因此您可以编写:

import operator

class Condition:
    def __init__(self, value1, op, value2):
        self.value1 = value1
        self.op = op
        self.value2 = value2
    def test(self):
        return self.op(self.value1, self.value2)

condition = Condition(5, operator.gt, 4)

if condition.test():
    print("passed")
else:
    print("failed")

如果要传递字符串而不是函数,则可以使用dict来映射它们:

import operator

OPERATOR_SYMBOLS = {
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>': operator.gt,
    '>=': operator.ge
}

class Condition:
    def __init__(self, value1, op, value2):
        self.value1 = value1
        self.op = op
        self.value2 = value2
    def test(self):
        return OPERATOR_SYMBOLS[self.op](self.value1, self.value2)

condition = Condition(5, '>', 4)

if condition.test():
    print("passed")
else:
    print("failed")

答案 1 :(得分:1)

您可以使用eval('{}{}{}'.format(v1,op,v2))

答案 2 :(得分:1)

The operator module提供了各种比较器作为函数,因此您可以从字符串形式映射到函数以执行比较:

import operator

class Condition:

    cmp_to_op = {'==': operator.eq,
                  '!=': operator.ne,
                  '<': `operator.lt,
                  '<=': `operator.le,
                  '>': `operator.gt,
                  '>=': `operator.ge}

    def __init__(self, value1, operator, value2):
        self.value1 = value1
        self.operator = self.cmp_to_op(operator)
        self.value2 = value2

    def test(self):
        # No need for if return True else return False; comparison already returns
        # True or False for normal objects
        return self.operator(self.value1, self.value2)