您应该实现该方法__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可能在对象的生存期内更改),则建议仅将实例保留为不可散列。
如果要对不可变类型进行建模,则还应该实现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__可能包含不可比较或不可哈希的类型。
注意:请注意,在Python 3之前,您可能需要使用__cmp__而不是__eq__。Python 2用户可能还想实现__ne__,因为不等式的明智的默认行为(即反转相等结果)将不会在Python 2中自动创建。