我创建了以下类:
class Image(object):
def __init__(self, extension, data, urls=None, user_data=None):
self._extension = extension
self._data = data
self._urls = urls
self._user_data = user_data
self._hex_digest = hashlib.sha1(self._data).hexDigest()
Run Code Online (Sandbox Code Playgroud)
当所有值相等时,图像应该相等.因此我写道:
def __eq__(self, other):
if isinstance(other, Image) and self.__dict__ == other.__dict__:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.__dict__ < other.__dict__
...
Run Code Online (Sandbox Code Playgroud)
但该__hash__方法应该如何?相等的图像应该返回相等的哈希值...
def __hash__(self):
# won't work !?!
return hash(self.__dict__)
Run Code Online (Sandbox Code Playgroud)
我尝试使用__eq__, __ne__, __lt__, __hash__, ...推荐的方式吗?
你真的需要订购图像吗?如果没有,我会放弃该__lt__方法.因为__hash__,请记住,两个不相等的对象可以具有相同的哈希值,因此您可以选择一个属性(或使用多个属性的元组)来派生哈希码.例如:
def __hash__(self):
return hash(self._hex_digest)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
568 次 |
| 最近记录: |