Re: How to define a class that can act as dictionary key?

2009-09-15 Thread Bruno Desthuilliers
Lambda a écrit : Hi, I'd like to define a class to use it as a dictionary key: Others already answered (define the __hash__ method). Just one point: the value returned by the __hash__ method should not change for the lifetime of the object. So if you use instance attributes to compute the

Re: How to define a class that can act as dictionary key?

2009-09-15 Thread Paul Rubin
Christian Heimes writes: > > def __hash__(self): return (self.term, self.doc_freq) > > > > is probably the easiest. > > The __hash__ function must return an integer: Oh oops. Try: def __hash__(self): return hash((self.term, self.doc_freq)) -- http://mail.python.org/mailman/listinfo/py

Re: How to define a class that can act as dictionary key?

2009-09-15 Thread Christian Heimes
Paul Rubin schrieb: > Lambda writes: >> When I run it, it says "TypeError: unhashable instance" >> >> It looks like I can't use the new class object as the dictionary key. >> What should I do? > > You have to add a __hash__ method. Untested: > > def __hash__(self): return (self.term, self.d

Re: How to define a class that can act as dictionary key?

2009-09-15 Thread Xavier Ho
On Tue, Sep 15, 2009 at 9:47 PM, Lambda wrote: > When I run it, it says "TypeError: unhashable instance" > > I believe you need to implement __hash__() for the class. Make sure your class returns a unique identifier for a certain value. -- http://mail.python.org/mailman/listinfo/python-list

Re: How to define a class that can act as dictionary key?

2009-09-15 Thread Paul Rubin
Lambda writes: > When I run it, it says "TypeError: unhashable instance" > > It looks like I can't use the new class object as the dictionary key. > What should I do? You have to add a __hash__ method. Untested: def __hash__(self): return (self.term, self.doc_freq) is probably the easiest

How to define a class that can act as dictionary key?

2009-09-15 Thread Lambda
Hi, I'd like to define a class to use it as a dictionary key: class dict_entry: def __init__(self, term = "", doc_freq = 0): self.term = term self.doc_freq = doc_freq def __cmp__(self, entry): return isinstance(entry, dict_entry) and cmp(self.term, entry.term) def __str__(self