Trouble with max() and __cmp__()

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

    #1

    Trouble with max() and __cmp__()

    My code:

    class Policy(list):
    def __cmp__(self,ot her):
    return cmp(self.fitnes s,other.fitness )

    j = Policy()
    j.fitness = 3
    k = Policy()
    k.fitness = 1
    l = Policy()
    l.fitness = 5
    print max([j,k,l]).fitness

    prints 3, when I was expecting it to print 5. What have I done wrong?

    Thanks for the help,
    THN

  • Wojciech =?ISO-8859-2?Q?Mu=B3a?=

    #2
    Re: Trouble with max() and __cmp__()

    Thomas Nelson wrote:
    My code:
    >
    class Policy(list):
    def __cmp__(self,ot her):
    return cmp(self.fitnes s,other.fitness )
    Define method __gt__.

    Comment

    • Thomas Nelson

      #3
      Re: Trouble with max() and __cmp__()



      On Jan 28, 3:13 pm, Wojciech Muła
      <wojciech_m...@ poczta.null.one t.pl.invalidwro te:
      >Define method __gt__.
      This works, thanks. I was a little surprised though. is __cmp__ used
      by any builtin functions?

      Thanks,
      THN

      Comment

      • =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=

        #4
        Re: Trouble with max() and __cmp__()

        Thomas Nelson schrieb:
        On Jan 28, 3:13 pm, Wojciech Muła
        <wojciech_m...@ poczta.null.one t.pl.invalidwro te:
        >Define method __gt__.
        >
        This works, thanks. I was a little surprised though. is __cmp__ used
        by any builtin functions?
        It is used by max() if the object doesn't implement __gt__.

        Regards,
        Martin

        Comment

        • Gabriel Genellina

          #5
          Re: Trouble with max() and __cmp__()

          At Sunday 28/1/2007 18:21, Thomas Nelson wrote:
          ><wojciech_m... @poczta.null.on et.pl.invalidwr ote:
          Define method __gt__.
          >
          >This works, thanks. I was a little surprised though. is __cmp__ used
          >by any builtin functions?
          The problem is, rich comparison functions take precedence over
          __cmp__, so if your base class (list in this case) already defines
          rich comparison, you have to redefine them all.
          For simple cases, you can just redefine __cmp__ and reimplement all
          others __gt__, __lt__ etc using it.


          --
          Gabriel Genellina
          Softlab SRL






          _______________ _______________ _______________ _____
          Preguntá. Respondé. Descubrí.
          Todo lo que querías saber, y lo que ni imaginabas,
          está en Yahoo! Respuestas (Beta).
          ¡Probalo ya!


          Comment

          Working...