假设我有一些Person实体,我想知道其中一个是否在列表中:
person in people?
我不关心“对象ID”是什么,只关心它们的属性是否相同。因此我将此放入我的基类中:
# value comparison only
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
但是为了能够在集合中测试相等性,我还需要定义哈希,所以……
# sets use __hash__ for equality comparison
def __hash__(self):
return (
self.PersonID,
self.FirstName,
self.LastName,
self.etc_etc...
).__hash__()
问题是我不想列出每个属性,也不想在属性更改时每次修改哈希函数。
那么这样做可以吗?
# sets use __hash__ for equality comparison
def __hash__(self):
values = tuple(self.__dict__.values())
return hash(values)
这个方案是否明智,且性能损失不会太大?考虑到是一个 web 应用的情况。
非常感谢。