Re: Overloading comparison method (__cmp__)
Guido.van.Rossum@cwi.nl
Thu, 16 Feb 1995 16:40:29 +0100
> I would like to implement a new class called Variable. A Variable should
> have knowledge about an interval of values which can be assigned to
> the variable. To set the borders of the interval I would like to use
> the comparison methods <= and >=. To assign a new value to a Variable
> I want to use ==. My code currently looks like this:
>
[...]
>
> I would like to add methods called '<=' which stands for SetUpperBound and
> a method called '>=' which does SetLowerBound. An additional method called
> '==' should call SetValue.
>
> Python does not allow to do this, because it only offers the method __cmp__
> to be overlayd. It would be nice if this method could query the original
> type of comparison requested. It would be still better if __cmp__ could be
> replaced by different methods, one for each of the comparsion types <=, <,
> ==, >, >=, !=.
>
> Or is there anything I have overlooked?
The only thing you have overlooked is a matter of style. In Python,
overloading of <= or >= with something that's not a comparison is
considered bad style.
Python requires that every object type or class has a comparison
operator (and if a class does not define one it provides a default
comparison). This operator can be used implicitly when the object is
contained in a list and the list is sorted or its minimum or maximum
is requested. (And there is also the matter that Python defines '=='
in such a way that every object is always equal to itself.)
In any case, since your variables contain values, I expect that some
later version of your program may also want to compare them to each
other, so using some comparison operators for assignments would cause
problems later anyway.
--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>