__cmp__ method

Jon Clements joncle at googlemail.com
Wed Jun 14 19:23:59 EDT 2006


This probably isn't exactly what you want, but, unless you wanted to do
something especially with your own string class, I would just pass a
function to the sorted algorithm.

eg:

sorted( [a,b,c], cmp=lambda a,b: cmp(len(a),len(b)) )

gives you the below in the right order...

Never tried doing what you're doing, but something about builtin types,
and there's a UserString module...

Hope that helps a bit anyway,

Jon.

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
>
> >>> class myStr(str):
>     def __init__(self, s):
>         str.__init__(self, s) # Ensure super class is initialized
>     def __cmp__(self, other):
>         return cmp(len(self), len(other))
>
> >>> a = myStr('abc')
> >>> b = myStr('Personal')
> >>> c = myStr('Personal firewall')
> >>> sorted([c, b, a])
> ['Personal', 'Personal firewall', 'abc']
> >>>




More information about the Python-list mailing list