vendredi 24 août 2018

Python - Using Strings As A Condition Operator In An If Statements

In Python is it possible to use a string as an operator in an if statement condition?

I would like to have an object with two values and an operator to test them. For Example:

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

Thanks.

Aucun commentaire:

Enregistrer un commentaire