operator overloading

Ken Seehof 12klat at sightreader.com
Mon Jun 5 18:02:47 EDT 2000


Emile van Sebille wrote:

> Here's a quick example of using __cmp__
>
> >>> class Test:
>  def __init__(self,a):
>   self.a = a
>  def __cmp__(self,other):
>   return self.a < other.a
>
> >>> a = Test(3)
> >>> b = Test(4)
> >>> print a<b
> 0
> >>> print a>b
> 1
>
> HTH,
>
> Emile van Sebille
> emile at fenx.com
> -------------------

Um.  No.  Not exactly.  Usually 1 designates "true" and 0 designates
"false" unless I'm mistaken.  Also IMHO, > means "greater than" and <
means "less than".  BTW there is yet another comparison operator == than
means "equal to".  :-)

The return value of __cmp__ should be -1, 0, 1 for <, ==, >,
respectively.

The following more closely conforms to these conventions:

>>> class Test:
...  def __init__(self,a):
...   self.a = a
...  def __cmp__(self,other):
...   if self.a == other.a:
...    return 0
...   elif self.a < other.a:
...    return -1
...   else:
...    return 1
...
>>> a = Test(1)
>>> b = Test(2)
>>> c = Test(2)
>>> a<b, a>b, a==b, a!=b
(1, 0, 0, 1)
>>> b==c, b<c, b!=c
(1, 0, 0)

-- Ken Seehof
kens at sightreader.com

> ----- Original Message -----
> From: <kazan at kazan.fenx.com>
> Newsgroups: comp.lang.python
> To: <python-list at python.org>
> Sent: Monday, June 05, 2000 1:01 PM
> Subject: operator overloading
>
> > Hello
> >
> > How can I overload the less than operator?
> > learning python did mention something about __cmp__ but
> did
> > not provide any examples.
> >
> >
> > Thanks in advance
> >
> > Erling
> > --
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20000605/98d62490/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 12klat.vcf
Type: text/x-vcard
Size: 343 bytes
Desc: Card for Ken Seehof
URL: <http://mail.python.org/pipermail/python-list/attachments/20000605/98d62490/attachment.vcf>


More information about the Python-list mailing list