python - 如何在 python 中定义自定义比较 (0 < mytype)?

标签 python

所以我目前正在(ab)使用 python 符号来创建领域特定语言。作为其中的一部分,我将覆盖比较函数以返回非 bool 值。

因此,对于 (mytype1 < mytype2) 和 (mytype < 0),我可以通过定义 __lt__() 魔术方法轻松地做到这一点。

但是,我不知道如何为 (0 < mytype) 这样做,因为可能需要在内置 int 类型上定义魔术方法。似乎没有用于数字运算的 __rlt__() 函数。

如果 lhs 是 int 类型(在 python3 中),我如何添加对这种比较的支持?

最佳答案

根据 the documentation __lt__() 的反射(reflect)形式是 __gt__()

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.

关于python - 如何在 python 中定义自定义比较 (0 < mytype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37514787/

相关文章:

python +Excel : how to programmatically insert picture into comment

python - 无法使用 subprocess.Popen 执行 shell 命令

Python 类实例变量继承机制

python - 在 tensorflow 中重新分配非变量张量

java - 在Python中使用类对象作为其他类函数的参数

python - 在 Visual Studio Express 2013 中自动生成 python 文档字符串

python - 动态调整 Tkinter Canvas 文本

python - 如何理解文档中的pydoc参数

python web 套接字握手不起作用

python - 如何根据本地目录中的 requirements.txt 文件使用 pip 安装软件包?