how to overload operator "< <" (a < x < b)?

Robert Lehmann stargaming at gmail.com
Fri Aug 7 15:59:45 CEST 2009


On Fri, 07 Aug 2009 08:50:52 -0400, Benjamin Kaplan wrote:

> On Fri, Aug 7, 2009 at 8:00 AM, dmitrey<dmitrey.kroshko at scipy.org>
> wrote:
>> hi all,
>> is it possible to overload operator "<  <"? (And other like this one,
>> eg "<=  <=", ">  >", ">=  >=")
>> Any URL/example?
>> Thank you in advance, D.
> 
> That isn't an operator at all. Python does not support compound
> comparisons like that. You have to do "a > b and b > c".

Python actually allows you to chain comparison operators, automatically 
unpacking ``a > b > c`` to ``a > b and b > c``::

>>> class C(object):
...   def __lt__(self, other):
...     print self, "LESS-THAN", other
...     return True
... 
>>> a = C(); b = C(); x = C()
>>> a < x < b
<__main__.C object...> LESS-THAN <__main__.C object...>
<__main__.C object...> LESS-THAN <__main__.C object...>
True

>>> x = 42
>>> 40 < x < 50 # between 40 and 50
True
>>> 50 < x < 60 # between 50 and 60
False
>>> 1 == True < 2 == 2.0 < 3 < 4 != 5 > 0 # yikes, unreadable! but legal.
True
>>> # same as: (1 == True) and (True < 2) and (2 == 2.0) ...

HTH,

-- 
Robert "Stargaming" Lehmann




More information about the Python-list mailing list