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