Trouble with max() and __cmp__()

T

Thomas Nelson

My code:

class Policy(list):
def __cmp__(self,other):
return cmp(self.fitness,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
 
G

Guest

Thomas said:
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
 
G

Gabriel Genellina

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!
http://www.yahoo.com.ar/respuestas
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top