cmp of multiple attributes (WAS: Why are tuples immutable?)

Steven Bethard steven.bethard at gmail.com
Thu Dec 16 16:18:57 EST 2004


Roy Smith wrote:
> class Property:
>     def __init__ (self, block, lot, zoning="Unknown"):
>         self.block = block
>         self.lot = lot
>         self.zoning = zoning
> 
>     def __hash__ (self):
>         return (self.block + self.lot)
> 
>     def __cmp__ (self, other):
> 	# I wish there was a less verbose way to do this!
>         if self.block < other.block:
>             return -1
>         if self.block > other.block:
>             return 1
>         if self.lot < other.lot:
>             return -1
>         if self.lot > other.lot:
>             return 1
>         return 0

Does this do what you want?

 >>> class Property(object):
...     def __init__(self, block, lot):
...         self.block, self.lot = block, lot
...     def __cmp__(self, other):
...         return (cmp(self.block, other.block) or
...                 cmp(self.lot, other.lot))
...
 >>> for i in (0, 1):
...     for j in (0, 1):
...         for k in (0, 1):
...             for l in (0, 1):
...                 print i, j, k, l, cmp(Property(i,j),Property(k,l))
...
0 0 0 0 0
0 0 0 1 -1
0 0 1 0 -1
0 0 1 1 -1
0 1 0 0 1
0 1 0 1 0
0 1 1 0 -1
0 1 1 1 -1
1 0 0 0 1
1 0 0 1 1
1 0 1 0 0
1 0 1 1 -1
1 1 0 0 1
1 1 0 1 1
1 1 1 0 1
1 1 1 1 0

Steve



More information about the Python-list mailing list