【发布时间】:2012-02-13 04:02:35
【问题描述】:
考虑这个sn-p:
class SomeClass(object):
def __init__(self, someattribute="somevalue"):
self.someattribute = someattribute
def __eq__(self, other):
return self.someattribute == other.someattribute
def __ne__(self, other):
return not self.__eq__(other)
list_of_objects = [SomeClass()]
print(SomeClass() in list_of_objects)
set_of_objects = set([SomeClass()])
print(SomeClass() in set_of_objects)
计算结果为:
True
False
谁能解释为什么'in'关键字对集合和列表有不同的含义? 我本来希望两者都返回 True,尤其是在被测试的类型定义了相等方法时。
【问题讨论】:
-
请参阅stackoverflow.com/questions/7549709/… .. 顺便说一句,在 Python 3 中运行此代码会提示正在发生的事情:“TypeError: unhashable type: 'SomeClass'”
-
谢谢大家,现在一切都清楚了。
-
顺便说一句,您知道您的
someattribute是 class 属性而不是 instance 属性,对吧?你有听说过__init__,对吧? -
@Karl:是的,为现实主义而编辑