__cmp__ method

bruno at modulix onurb at xiludom.gro
Thu Jun 15 04:57:48 EDT 2006


JH wrote:
> Hi
> 
> Can anyone explain to me why the following codes do not work? I want to
> try out using __cmp__ method to change the sorting order. I subclass
> the str and override the __cmp__ method so the strings can be sorted by
> the lengh. I expect the shortest string should be in the front. Thanks

AFAIK (please a Guru correct me if I'm wrong), __cmp__ is used as a
fallback when other comparison operators ( __lt__ etc) are not implemented :

>>> class MyStr(str):
...     def __lt__(self, other):
...             return len(self) < len(other)
...     def __le__(self, other):
...             return len(self) <= len(other)
...     def __gt__(self, other):
...             return len(self) > len(other)
...     def __ge__(self, other):
...             return len(self) >= len(other)
...
>>> items = [MyStr("lolo lala"), MyStr("lolo"), MyStr("alal"), MyStr("a")]
>>> sorted(items)
['a', 'lolo', 'alal', 'lolo lala']
>>>

But anyway, all this is a WTF. Just using the correct params for sorted
is enough:
>>> items2 = ['lolo lala', 'lolo', 'alal', 'a']
>>> sorted(items2, key=len)
['a', 'lolo', 'alal', 'lolo lala']


> 
>>>>class myStr(str):
> 
>     def __init__(self, s):
>         str.__init__(self, s) # Ensure super class is initialized

This is useless. If you don't override it, parent's init will be called
anyway.

(snip)

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list