overwrite set behavior

Maric Michaud maric at aristote.info
Thu Sep 4 15:07:34 CEST 2008


Le Thursday 04 September 2008 14:31:23 Michele Petrazzo, vous avez écrit :
> Marco Bizzarri wrote:
> > looking at the source, maybe you could create a subclass of Set
> > redefining the __contains__ method?
>
> Made some tries, but __contains__ are never called
>

No, __contains__ is only called  with "in" operator, not for internal hashing. 
Anyway this solution is bad, you'll need to compare the new element with all 
the set contain, which would result in a O(n) algorithm for adding elements 
to the set in place of the O(1) it use.

The right way to go is one like Diez show you in a previous post.

>  >>> class foo(set):
> ...  def __contains__(self, value):
> ...   print value
> ...
>  >>> a = foo((1,2))
>  >>>



-- 
_____________

Maric Michaud



More information about the Python-list mailing list