Q: Subclassing dict and __cmp__

Hans Nowak wurmy at earthlink.net
Sun Oct 20 19:06:43 CEST 2002


Miki Tebeka wrote:

>>>>class H(dict):
>>>
> 	def __cmp__(self, other):
> 		'''Compare only x's'''
> 		if self['x'] == other['x']:
> 			return 0
> 		return 1

What do you want this code to do when 'x' doesn't exist in either of the 
dictionaries?

Also, __cmp__ doesn't return just 0 or 1... it is supposed to return -1 if self 
< other, 0 if self == other, and 1 if self > other.

Third, overriding just __cmp__ may not be enough. There's also the __eq__ 
method. Here's my version (untested and all that), with print statements so 
it's clear which method is called:

 >>> class H(dict):
	def __cmp__(self, other):
		print 'wheee!'
		return cmp(self['x'], other['x'])
	def __eq__(self, other):
		print '__eq__ called'
		return self['x'] == other['x']

 >>> h1 = H({'x': 2})
 >>> h2 = H({'x': 3})
 >>> h1 > h2
wheee!
0
 >>> h2 > h1
wheee!
1
 >>> h1 == h2
__eq__ called
0
 >>> h1 == h1
__eq__ called
1

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html




More information about the Python-list mailing list