Dictionary in Python
Alex
alex at somewhere.round.here
Mon Mar 13 14:38:09 EST 2000
> Python does not actually hash on the object; instead, it hashes on the
> reference to the object (sort of, this isn't quite technically
> accurate, but I'm not familiar enough with the internals to make it
> more accurate) -- this is the reason why Python requires immutables as
> keys.
Hi, Aahz.
I was under the impression that it hashes on the value of hash (object),
and that if you made a class with __hash__ and __cmp__ methods, you
could happily use instances of that class as keys. I made a little
class like that recently, it seemed to work that way:
class Pattern:
def __init__(self, characters, offsets):
assert len(characters) == len(offsets) + 1
self.characters = characters
self.offsets = offsets
def __hash__(self):
return hash((self.characters, self.offsets))
def __cmp__(self,other):
return cmp((self.characters, self.offsets),
(other.characters, other.offsets))
def __str__(self):
output = []
for character, offset in map(None, self.characters[: -1],
self.offsets):
output.extend([character, offset*'.'])
output.append(self.characters[-1])
return string.join(output, '')
def __repr__(self):
return 'Pattern(\'%s\', %s)' % (self.characters, self.offsets)
def __len__(self):
return len(self.characters)
def positions(self, start):
positions = [start]
for offset in self.offsets:
positions.append(positions[-1] + offset)
return positions
Alex.
More information about the Python-list
mailing list