你应该实现该方法__eq__ https://docs.python.org/3/reference/datamodel.html#object.__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
and bar
可能会在对象的生命周期内更改值),那么建议将实例保留为不可散列。
如果您正在建模不可变类型,则还应该实现数据模型挂钩__hash__ https://docs.python.org/3/reference/datamodel.html#object.__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__ https://portingguide.readthedocs.io/en/latest/comparisons.html#rich-comparisons代替__eq__
。 Python 2 用户可能还想实现__ne__ https://docs.python.org/2/reference/datamodel.html#object.__ne__,因为在 Python 2 中不会自动创建不等式的合理默认行为(即反转等式结果)。