Python operator - zhongjiajie/zhongjiajie.github.com GitHub Wiki

operator

operator — Standard operators as functions

example

通过str运算符运算出结果

这样做的好处是用户直接调用运算符,不需要了解operator的操作,程序打日志可以直接打印运算符的类型,如果传operator对象,会就比较难打印运算符类型了.

import operator

def get_operator_fn(op):
    return {
        '+' : operator.add,
        '-' : operator.sub,
        '*' : operator.mul,
        '/' : operator.div,
        '%' : operator.mod,
        '^' : operator.xor,
        }[op]

def eval_binary_expr(op1, oper, op2):
    op1,op2 = int(op1), int(op2)
    return get_operator_fn(oper)(op1, op2)

print eval_binary_expr(*("1 + 3".split()))
print eval_binary_expr(*("1 * 3".split()))
print eval_binary_expr(*("1 % 3".split()))
print eval_binary_expr(*("1 ^ 3".split()))

⚠️ **GitHub.com Fallback** ⚠️