В руководстве сказано:
в общем,
__lt__()
и__eq__()
достаточно, если вам нужны общепринятые значения операторов сравнения
Но я вижу ошибку:
> 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__()
исправляет это, но означает, что я не понимаю, каковы минимальные требования для заказа...
Спасибо, Эндрю
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. Arguments to rich comparison methods are never coerced.
- person agf   schedule 07.04.2012