gre*_*iod 2 python testing operator-keyword
是否有可能/如下面的示例中那样通过一系列运算符进行迭代?
a, b = 5, 7
for op in (+, -, *, /):
print(a, str(op), b, a op b)
Run Code Online (Sandbox Code Playgroud)
一种可能的用例是在某种抽象数据类型上重载各种运算符的情况下对这些运算符的实现进行测试。
您可以使用操作员模块。
for op in [('+', operator.add), ('-', operator.sub), ('*', operator.mul), ('/', operator.div)]:
print("{} {} {} = {}".format(a, op[0], b, op[1](a, b)))
Run Code Online (Sandbox Code Playgroud)