Python代码仅数学运算符重复,如何编写通用函数消除冗余?
问题解答
当然可以实现,Python中运算符本身无法直接作为参数传递,但我们可以通过两种方式把运算符封装为可调用对象传入函数:
方法1:使用内置operator模块(推荐)
Python标准库自带的operator模块已经封装了所有基础运算符对应的可调用函数,不需要自己手写运算逻辑,性能和可读性都更好:
import operator # 通用计算函数,a、b为运算数,op为传入的运算符函数 def operator_modularity(a, b, op): return op(a, b) # 调用示例 a = 10 b = 2 x1 = operator_modularity(a, b, operator.add) # 等价于a+b x2 = operator_modularity(a, b, operator.sub) # 等价于a-b x3 = operator_modularity(a, b, operator.mul) # 等价于a*b x4 = operator_modularity(a, b, operator.truediv) # 等价于a/b
常用运算符对应的operator函数对照:
- 加法
+:operator.add - 减法
-:operator.sub - 乘法
*:operator.mul - 除法
/:operator.truediv(Python3普通除法)、operator.floordiv(//取整除法) - 取余
%:operator.mod - 幂运算
**:operator.pow
方法2:传入lambda匿名函数
如果不想引入额外模块,或者需要自定义特殊运算规则,可以直接传入lambda表达式作为运算逻辑:
def operator_modularity(a, b, op): return op(a, b) a = 10 b = 2 x1 = operator_modularity(a, b, lambda x, y: x + y) x2 = operator_modularity(a, b, lambda x, y: x - y)
如果你需要固定a/b不需要每次传参,也可以把两个运算数放在函数外层作用域,调整为你给出的伪代码的形式:
import operator a = 10 b = 2 def operator_modularity(op): return op(a, b) x1 = operator_modularity(operator.add)
内容的提问来源于stack exchange,提问作者GalSuchetzky
相关产品推荐
相关产品推荐

