如何在Python中为自定义类正确重写__hash__与__eq__?
在python中,若要让自定义类的实例可哈希(例如放入集合或作为字典键),必须同时重写 __eq__ 和 __hash__。核心原则是:相等的对象必须有相同的哈希值,且不可变属性构成的元组应作为哈希依据。

如何确保相等性逻辑的一致性?
当两个对象的 __eq__ 返回 True 时,它们的 __hash__ 返回值必须相同。如果只重写了 __eq__ 而未重写 __hash__,Python 会将该类的 __hash__ 设为 None,导致实例不可哈希。

class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return False
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2) # True
print(hash(p1) == hash(p2)) # True
上述代码展示了 Point 类如何通过比较坐标来判断相等性,并通过坐标元组的哈希值来保证一致性。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
如何处理可变属性的哈希冲突?
如果类的属性是可变的,直接将其用于哈希计算会导致严重问题,因为对象修改后哈希值改变,但其在集合或字典中的位置不变,导致无法检索。

class MutablePoint:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, MutablePoint):
return False
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
mp1 = MutablePoint(1, 2)
s = {mp1}
mp1.x = 3 # 修改属性
print(mp1 in s) # False,因为哈希值变了
此示例表明,修改 MutablePoint 的 x 属性后,其哈希值发生变化,导致原本在集合中的对象变得“丢失”。因此,建议仅对不可变属性进行哈希计算,或在设计类时避免使用可变属性作为哈希依据。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










