python - 数学运算符作为函数参数

use*_*332 2 python

我有这段代码.

def maths(operator):
   #different math here..

   final = final + number #i want to use the operator arg here
Run Code Online (Sandbox Code Playgroud)

.后来,我想把它称为数学('+')或数学(' - '),所以我不必每次都使用相同的代码.

Sin*_*ion 6

您正在寻找操作员模块

def maths(accum):
    #...
    final = accum(final, number):

x = maths(operator.mul)
Run Code Online (Sandbox Code Playgroud)