我有一个MyClass
类,其中包含两个成员变量foo
和bar
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
我有这个类的两个实例,每个实例都有相同的foo
和bar
值
x = MyClass('foo', 'bar')
y = MyClass('foo', 'bar')
但是,当我比较它们是否相等时,Python返回False
>>> x == y
False
怎样才能让python认为这两个对象相等呢?
发布于 2009-08-04 12:47:35
您应该实现方法__eq__
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __eq__(self, other):
if not isinstance(other, MyClass):
# don't attempt to compare against unrelated types
return NotImplemented
return self.foo == other.foo and self.bar == other.bar
现在它输出:
>>> x == y
True
请注意,实现__eq__
将自动使您的类的实例不可散列,这意味着它们不能存储在集合和字典中。如果您没有对不可变类型建模(例如,如果属性foo
和bar
可能会在对象的生命周期内更改该值),那么建议将实例保留为不可散列的。
如果要对不可变类型进行建模,则还应实现数据模型挂钩__hash__
class MyClass:
...
def __hash__(self):
# necessary for instances to behave sanely in dicts and sets.
return hash((self.foo, self.bar))
一般的解决方案,比如遍历__dict__
并比较值的想法,是不可取的-它永远不会是真正的通用的,因为__dict__
中可能包含不可比较或不可散列的类型。
注意:请注意,在Python3之前,您可能需要使用__cmp__
而不是__eq__
。Python2用户可能还想实现__ne__
,因为在Python2中不会自动创建一个合理的不等式默认行为(例如,反转相等结果)。
发布于 2009-08-04 12:15:43
您可以覆盖对象中的rich comparison operators。
class MyClass:
def __lt__(self, other):
# return comparison
def __le__(self, other):
# return comparison
def __eq__(self, other):
# return comparison
def __ne__(self, other):
# return comparison
def __gt__(self, other):
# return comparison
def __ge__(self, other):
# return comparison
如下所示:
def __eq__(self, other):
return self._id == other._id
发布于 2009-08-04 12:15:19
在您的类中实现__eq__
方法;如下所示:
def __eq__(self, other):
return self.path == other.path and self.title == other.title
编辑:如果希望对象在且仅当它们具有相等的实例字典时比较相等:
def __eq__(self, other):
return self.__dict__ == other.__dict__
https://stackoverflow.com/questions/1227121
复制相似问题