Beginner question please help!

Mark McEahern marklists at mceahern.com
Thu Feb 14 12:00:30 EST 2002


Well, for starters, what are x and y?  There's a built-in cmp function:

>>> cmp(4, 5)
-1

If you define your own classes and you want them to allow comparison by
value, you can simply define the special method __cmp__ for them.

#! /usr/bin/env python

class Foo:

	def __init__(self, value=None):
		self.value = value

	def __cmp__(self, other):
		return cmp(self.value, other.value)

f = Foo(4)
g = Foo(5)

print "cmp(f, g) == %d" % (cmp(f, g))
print "f < g == %d" % (f < g)
print "f == g == %d" % (f == g)
print "f > g == %d" % (f > g)

// mark

> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Michael Tu
> Sent: Thursday, February 14, 2002 8:43 AM
> To: python-list at python.org
> Subject: Beginner question please help!
>
>
> Hello,
>
> I am trying to do the following exercise but after spending couple of
> hours without any luck, I think it is time to get some helps. Thank
> you in advance.
>
> Write a compare function that return 1 if x > y, 0 if x == y, and -1
> if x < y.
>
> Mike
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>





More information about the Python-list mailing list