比较对象实例的属性是否相等 [英] Compare object instances for equality by their attributes
问题描述
我有一个类 MyClass
,其中包含两个成员变量 foo
和 bar
:
I have a class MyClass
, which contains two member variables foo
and bar
:
class MyClass:
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
我有两个实例此类,每个类别的 foo
和 bar
具有相同的值:
I have two instances of this class, each of which has identical values for foo
and bar
:
x = MyClass('foo', 'bar')
y = MyClass('foo', 'bar')
但是,当我比较它们是否相等时,Python返回 False
:
However, when I compare them for equality, Python returns False
:
>>> x == y
False
如何使python认为这两个对象相等? / p>
How can I make python consider these two objects equal?
推荐答案
您应实现方法 __ eq __
:
You should implement the method __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
可能会在
Note that implementing __eq__
will automatically make instances of your class unhashable, which means they can't be stored in sets and dicts. If you're not modelling an immutable type (i.e. if the attributes foo
and bar
may change value within the lifetime of your object), then it's recommend to just leave your instances as unhashable.
如果要对不可变类型进行建模,还应该实现数据模型挂钩 __ hash __
:
If you are modelling an immutable type, you should also implement the datamodel hook __hash__
:
class MyClass:
...
def __hash__(self):
# necessary for instances to behave sanely in dicts and sets.
return hash((self.foo, self.bar))
一般解决方案,像循环遍历 __ dict __
这样的想法是不可取的-它永远不可能真正通用,因为 __ dict __
A general solution, like the idea of looping through __dict__
and comparing values, is not advisable - it can never be truly general because the __dict__
may have uncomparable or unhashable types contained within.
NB:请注意,在Python 3之前,您可能需要使用 __ cmp __
而不是 __ eq __
。 Python 2用户可能还想实现 __ ne __
,因为不等式的明智的默认行为(即反转相等结果)不会在Python 2中自动创建。
N.B.: be aware that before Python 3, you may need to use __cmp__
instead of __eq__
. Python 2 users may also want to implement __ne__
, since a sensible default behaviour for inequality (i.e. inverting the equality result) will not be automatically created in Python 2.
这篇关于比较对象实例的属性是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!