如果我理解正确,调用对象的 __cmp__() 函数是为了评估集合中的所有对象,同时确定对象是否是集合的成员或“在”集合中。 然而,这似乎不是集合的情况:
class MyObject(object):
def __init__(self, data):
self.data = data
def __cmp__(self, other):
return self.data-other.data
a = MyObject(5)
b = MyObject(5)
print a in [b] //evaluates to True, as I'd expect
print a in set([b]) //evaluates to False
那么如何在集合中测试对象成员资格呢?
最佳答案
将 __hash__
方法添加到您的类中会产生以下结果:
class MyObject(object):
def __init__(self, data):
self.data = data
def __cmp__(self, other):
return self.data - other.data
def __hash__(self):
return hash(self.data)
a = MyObject(5)
b = MyObject(5)
print a in [b] # True
print a in set([b]) # Also True!
关于python - 了解集合的 python 对象成员资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3679466/