Numeric comparison anomaly

Gerrit Holl gerrit at nl.linux.org
Wed Feb 19 15:28:32 CET 2003


> > I want to define an "infinite" numeric object, that's greater than
> > any regular number.  I do the obvious (Python 2.2):
> > 
> >     >>> class _infinity:
> >     ...   def __lt__(self, n): return 0
> >     ...   def __gt__(self, n): return 1
> >     ... 
> >     >>> infinity = _infinity()
> >     >>> infinity < 9
> >     0
> >     >>> infinity > 99999
> >     1
> >     >>> 99999 < infinity
> >     1
> > 
> > So far so good.  But here comes the surprise:
> > 
> >     >>> infinity >= 3
> >     0

You can use the __cmp__ overloader:

 21 >>> class A:
 21 ...  def __cmp__(self, other):
 21 ...   return 1
 21 ...
 22 >>> A() > 5
True
 23 >>> A() < 9
False
 24 >>> A() >= 3
True

See also:
http://www.python.org/dev/doc/devel/ref/customization.html#l2h-97

yours,
Gerrit.

-- 
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list