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

Carl Banks pavlovevidence at gmail.com
Sat Aug 8 00:01:47 EDT 2009


On Aug 7, 7:18 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> alex23 schrieb:
>
>
>
>
>
> > On Aug 7, 10:50 pm, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
> >> That isn't an operator at all. Python does not support compound
> >> comparisons like that. You have to do "a > b and b > c".
>
> > You know, it costs nothing to open up a python interpreter and check
> > your certainty:
>
> >>>> x = 10
> >>>> 1 < x < 20
> > True
>
> > This is a _very_ common pattern.
>
> >>>> class X(object):
> > ...   def __lt__(self, other):
> > ...     print 'in lt'
> > ...     return True
> > ...   def __gt__(self, other):
> > ...     print 'in gt'
> > ...     return True
> > ...
> >>>> x = X()
> >>>> 1 < x < 20
> > in gt
> > in lt
> > True
> >>>> 20 < x < 1
> > in gt
> > in lt
> > True
>
> > dmitrey: Diez' advice was the best you received.
>
> Not really. I didn't get the chaining, and Peter is right that for that
> there is no real overloading.

You can program __lt__, __gt__, and friends to return a closure with a
boolean value.  See my upcoming reply to the author.


Carl Banks



More information about the Python-list mailing list