Python 3 __cmp__ semantic change?
Aahz
aahz at pythoncraft.com
Sat Nov 22 10:31:16 EST 2008
In article <m2ljvc6nb7.fsf at googlemail.com>,
Arnaud Delobelle <arnodel at googlemail.com> wrote:
>
>There's a very simple way of emulating Fraction.__cmp__ in Python 3:
>
>def totally_ordered(cls):
> def __lt__(self, other): return self.cmp(other) < 0
> def __eq__(self, other): return self.cmp(other) == 0
> def __gt__(self, other): return self.cmp(other) > 0
> cls.__lt__ = __lt__
> cls.__eq__ = __eq__
> cls.__gt__ = __gt__
> # and same with __le__, __ge__
> return cls
>
>@totally_ordered
>class Fraction:
> def __init__(self, num, den=1):
> assert den > 0, "denomintator must be > 0"
> self.num = num
> self.den = den
> def cmp(self, other):
> return self.num*other.den - self.den*other.num
>
>
>It doesn't suffer the speed penalty incurred when defining comparison
>operators from __eq__ and __lt__.
That's true IIF __sub__() is not substantially slower than __cmp__();
however, your basic technique is sound and one can easily rewrite your
cmp() to use some other algorithm.
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
More information about the Python-list
mailing list