python的operator模块有什么意义?那里有许多明显多余的功能,我不明白为什么人们更愿意使用这些功能而不是其他方式来做同样的事情.
例如:
>>> import operator
>>> operator.truth(0)
False
>>> bool(0)
False
Run Code Online (Sandbox Code Playgroud)
似乎做了完全相同的事情.
它有时可以用来访问运算符的功能但作为一个功能.例如,要将两个数字相加,您可以这样做.
>> print(1 + 2)
3
Run Code Online (Sandbox Code Playgroud)
你也可以这样做
>> import operator
>> print(operator.add(1, 2))
3
Run Code Online (Sandbox Code Playgroud)
函数方法的一个用例可能是您需要编写一个计算器函数,该函数在给定简单公式的情况下返回答案.
import operator as _operator
operator_mapping = {
'+': _operator.add,
'-': _operator.sub,
'*': _operator.mul,
'/': _operator.truediv,
}
def calculate(formula):
x, operator, y = formula.split(' ')
# Convert x and y to floats so we can perform mathematical
# operations on them.
x, y = map(float, (x, y))
return operator_mapping[operator](x, y)
print(calculate('1 + 2')) # prints 3.0
Run Code Online (Sandbox Code Playgroud)
为了完整性和一致性。因为将所有运算符放在一处可以让您稍后进行动态查找:
getattr(operator, opname)(*arguments)
Run Code Online (Sandbox Code Playgroud)
由于某些操作是多余的而省略它们会破坏该目的。而且因为 Python 名称只是引用,所以向模块添加一个名称operator(只是另一个引用)既便宜又容易。