Python 中的一切都是对象
我们都知道这句话,所有 Python 爱好者(包括我)都喜欢它。在这方面,观察运营商很有趣。它们似乎不是物体,例如
>>> type(*) # or /, +, -, < ...
returns SyntaxError: invalid syntax
.
然而,在某些情况下,将它们视为对象可能会很有用。例如,考虑一个类似的函数
def operation(operand1, operand2, operator):
"""
This function returns the operation of two operands defined by the operator as parameter
"""
# The following line is invalid python code and should only describe the function
return operand1 <operator> operand2
So operation(1, 2, +)
会回来3
, operation(1, 2, *)
会回来2
, operation(1, 2, <)
会回来True
, etc...
为什么这没有在 python 中实现?或者是,如果,如何?
Remark: 我确实知道operator https://docs.python.org/3.8/library/operator.html模块,这也不适用于上面的示例函数。我也知道可以通过一种方式解决它,例如operations(operand1, operand2, '>')
并通过相应运算符的字符串表示找到所需的操作。然而,我询问不存在运算符对象能够作为函数中的参数传递的原因,例如就像其他所有 python 对象一样。