python - 算术运算符

标签 python math operators calculation arithmetic-expressions

如您所知,存在算术运算符,例如 +-。 有没有办法创建我自己的运算符,它可以在两个变量之间执行特定任务?

例如:

a, b = 2, 5
a '+' b == 7

我想做的事:

a 'my own operator' b == some_specific_value

最佳答案

有一个recipe了解如何模仿自定义中缀运算符。它创建一个自定义类 Infix 并实现 __or____ror__ 方法,然后允许按以下方式编写内容:

add = Infix(lambda x,y: x+y)
result = 1 |add| 2

关于python - 算术运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70173330/

相关文章:

python - 需要帮助在 os x 10.7 上安装 lxml

python - Pandas 中的 Rowwise

python 线程 - 请解释一下

python - 如何将增量添加到 python datetime.time?

python - 测量 float 列表的波动性或稳定性

C++ 计算器没有像我想象的那样工作

c# - 在 Unity3d 中导入数学时出错

python - 计算德州扑克中 5 张牌的抽牌次数

swift - 组合使用自定义运算符

matlab - 倍频程/Matlab : vectorising '==' operator?