Comparison function as class method: how?

Erik Max Francis max at alcyone.com
Thu May 8 17:43:47 EDT 2003


Jeff Stewart wrote:

> And how is someone supposed to know about staticmethod()?  I couldn't
> find
> it anywhere in the Tutorial, Language Reference Index, or Library
> Reference
> Index.  Is there a better place to go for documentation?

It is in the documentation, albeit not in a very easy place to find.

Note that since Python supports the concept of bound vs. unbound
methods, often you will find yourself not running into this problem as
you would in, say, C++, where it is quite frequent.  Instead you can
just define a normal method, and then pass a bound version of the
method, rather than an unbound one:

	class C:
	    ...
	    def compare(self, x, y):
	        ...

	c = C()
	L.sort(c.compare) # not C.compare)

Whether this or a static method is cleaner depends on your solution; if
you actually need to know instance data, for instance, then it would be
essential.

Having bound methods in Python is the equivalent of, in C++, wanting to
turn an instance and a member function pointer into a simple function
pointer, so that it's a simple callable.  The usual way this is solved
in C++ is with functors (which would be user-defined callables in
Python), since there's no concept of bound vs. unbound member function
pointers.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ When angry, count four; when very angry, swear.
\__/ Mark Twain
    Bosskey.net: Quake III Arena / http://www.bosskey.net/q3a/
 A personal guide to Quake III Arena.




More information about the Python-list mailing list