Access operator functions by symbol

后端 未结 4 537
臣服心动
臣服心动 2020-12-18 06:18

I need a function which takes one of python\'s operator symbols or keywords as a string, along with its operands, evaluates it, and returns the result. Like

4条回答
  •  旧巷少年郎
    2020-12-18 07:07

    You could use eval to generate lambda functions for the operators instead of using the operator module. Eval is generally bad practice, but I think for this purpose it's fine because it's nothing really crazy.

    def make_binary_op(symbol):
        return eval('lambda x, y: x {0} y'.format(symbol))
    
    operators = {}
    for operator in '+ - * / ^ % (etc...)'.split(' '):
        operators[operator] = make_binary_op(operator)
    
    operators['*'](3, 5) # == 15
    

提交回复
热议问题