Unexpected behavior for python set.__contains__

前端 未结 3 1399
盖世英雄少女心
盖世英雄少女心 2020-12-11 02:54

Borrowing the documentation from the __contains__ documentation

print set.__contains__.__doc__
x.__contains__(y) <==> y in x.
相关标签:
3条回答
  • 2020-12-11 03:35

    This is because CA doesn't implement __hash__

    A sensible implementation would be:

    def __hash__(self):
        return hash(self.name)
    
    0 讨论(0)
  • 2020-12-11 03:37

    For sets and dicts, you need to define __hash__. Any two objects that are equal should hash the same in order to get consistent / expected behavior in sets and dicts.

    I would reccomend using a _key method, and then just referencing that anywhere you need the part of the item to compare, just as you call __eq__ from __ne__ instead of reimplementing it:

    class CA(object):
      def __init__(self,name):
        self.name = name
    
      def _key(self):
        return type(self), self.name
    
      def __hash__(self):
        return hash(self._key())
    
      def __eq__(self,other):
        if self._key() == other._key():
          return True
        return False
    
      def __ne__(self,other):
        return not self.__eq__(other)
    
    0 讨论(0)
  • 2020-12-11 03:47

    A set hashes it's elements to allow a fast lookup. You have to overwrite the __hash__ method so that a element can be found:

    class CA(object):
      def __hash__(self):
        return hash(self.name)
    

    Lists don't use hashing, but compare each element like your for loop does.

    0 讨论(0)
提交回复
热议问题