在the manual是说:
in general,
__lt__()
and__eq__()
are sufficient, if you want the conventional meanings of the comparison operators
但我看到错误:
> assert 2 < three
E TypeError: unorderable types: int() < IntVar()
当我运行这个测试时:
from unittest import TestCase
class IntVar(object):
def __init__(self, value=None):
if value is not None: value = int(value)
self.value = value
def __int__(self):
return self.value
def __lt__(self, other):
return self.value < other
def __eq__(self, other):
return self.value == other
def __hash__(self):
return hash(self.value)
class DynamicTest(TestCase):
def test_lt(self):
three = IntVar(3)
assert three < 4
assert 2 < three
assert 3 == three
令我惊讶的是,当 IntVar()
在右边时,__int__()
没有被调用。我做错了什么?
添加 __gt__()
修复了这个问题,但这意味着我不明白订购的最低要求是什么......
谢谢, 安德鲁
最佳答案
Python 3.x 永远不会对运算符进行任何类型强制转换,因此在此上下文中不使用 __int__()
。对比
a < b
将首先尝试调用type(a).__lt__(a, b)
,如果返回NotImplemented
,它将调用type(b) .__gt__(b, a)
.
文档中的引述是关于对单一类型进行比较,上面的解释说明了为什么这对单一类型就足够了。
要使您的类型与 int
正确交互,您应该实现所有比较运算符,或使用 total_ordering
decorator在 Python 2.7 或 3.2 中可用。
关于python - 在 Python 3.1 中使用 Duck Typing 进行排序的最少方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10054937/