Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

list - Unexpected behavior for python set.__contains__

Borrowing the documentation from the __contains__ documentation

print set.__contains__.__doc__
x.__contains__(y) <==> y in x.

This seems to work fine for primitive objects such as int, basestring, etc. But for user-defined objects that define the __ne__ and __eq__ methods, I get unexpected behavior. Here is a sample code:

class CA(object):
  def __init__(self,name):
    self.name = name

  def __eq__(self,other):
    if self.name == other.name:
      return True
    return False

  def __ne__(self,other):
    return not self.__eq__(other)

obj1 = CA('hello')
obj2 = CA('hello')

theList = [obj1,]
theSet = set(theList)

# Test 1: list
print (obj2 in theList)  # return True

# Test 2: set weird
print (obj2 in theSet)  # return False  unexpected

# Test 3: iterating over the set
found = False
for x in theSet:
  if x == obj2:
    found = True

print found   # return True

# Test 4: Typcasting the set to a list
print (obj2 in list(theSet))  # return True

So is this a bug or a feature?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...