__cmp__ method

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • JH

    #1

    __cmp__ method

    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]

  • marek.rocki@wp.pl

    #2
    Re: __cmp__ method

    Python documentation says:[color=blue]
    >__cmp__( self, other)
    > Called by comparison operations if rich comparison (see above) is not defined.[/color]
    So it seems you have to redefine rich comparisons __lt__, __gt__,
    __eq__ etc as well.

    If all you need is change sorting order, why not use appropriate
    parameters of sorted() function (cmp=... or key=...)?

    Comment

    • Jon Clements

      #3
      Re: __cmp__ method

      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:
      [color=blue]
      > 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=green][color=darkred]
      > >>> class myStr(str):[/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=green][color=darkred]
      > >>> a = myStr('abc')
      > >>> b = myStr('Personal ')
      > >>> c = myStr('Personal firewall')
      > >>> sorted([c, b, a])[/color][/color]
      > ['Personal', 'Personal firewall', 'abc'][color=green][color=darkred]
      > >>>[/color][/color][/color]

      Comment

      • George Sakkis

        #4
        Re: __cmp__ method

        Jon Clements wrote:
        [color=blue]
        > 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...[/color]

        Or even better in 2.4 or later:
        sorted([a,b,c], key=len)

        George

        Comment

        • bruno at modulix

          #5
          Re: __cmp__ method

          JH wrote:[color=blue]
          > 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]

          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 :
          [color=blue][color=green][color=darkred]
          >>> class MyStr(str):[/color][/color][/color]
          .... 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)
          ....[color=blue][color=green][color=darkred]
          >>> items = [MyStr("lolo lala"), MyStr("lolo"), MyStr("alal"), MyStr("a")]
          >>> sorted(items)[/color][/color][/color]
          ['a', 'lolo', 'alal', 'lolo lala'][color=blue][color=green][color=darkred]
          >>>[/color][/color][/color]

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

          [color=blue]
          >[color=green][color=darkred]
          >>>>class myStr(str):[/color][/color]
          >
          > def __init__(self, s):
          > str.__init__(se lf, s) # Ensure super class is initialized[/color]

          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@xiludom. gro'.split('@')])"

          Comment

          Working...