<分区>
我问的原因纯粹是出于好奇。我可以看到,如果您事先不知道要对某些变量应用什么操作,或者在递归调用的某个级别应用不同的操作,或者它可能只是使某些事情更容易和/或更整洁。
虽然我只是猜测,这可能是一个非常糟糕的主意,但总的来说我只是好奇。
标签 python python-3.x
<分区>
我问的原因纯粹是出于好奇。我可以看到,如果您事先不知道要对某些变量应用什么操作,或者在递归调用的某个级别应用不同的操作,或者它可能只是使某些事情更容易和/或更整洁。
虽然我只是猜测,这可能是一个非常糟糕的主意,但总的来说我只是好奇。
最佳答案
您可以使用 operator
模块。
The
operator
module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example,operator.add(x, y)
is equivalent to the expressionx+y
. The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience.
所以在列表中存储“操作”很简单:
import operator
operations = [operator.add, operator.sub]
# add two numbers
s = operations[0](1, 2)
关于Python - 有没有办法将操作(+ - */)存储在列表中或作为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37142837/