← 中文资源

简体中文版本

值对象:__eq__ 与 __hash__ 保持一致

值对象相等只看字段不看身份:定义 __eq__ 后默认变不可哈希,必须同时给出一致的 __hash__,集合去重与 repr 输出才符合预期。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

a == b: True
a is b: False
set size: 1
repr: Money(950) | str: Money(950)
sum: Money(1950)
unhashable: unhashable type: 'Score'

实现说明

底层就是类 Money、Score和函数 __init__、__eq__、__hash__、__repr__。

使用要点

  • 跑完文件,输出里会留下标记——a == b:、a is b:、set size:。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件在加载时定义 __init__、__eq__、__hash__。

入口签名:def __init__(self, cents)

核心语句

return isinstance(other, Score) and self.value == other.value
try:
{Score(1)}
def __init__(self, cents):
    self.cents = cents
def __init__(self, value):
    self.value = value

代码示例

# 值对象:相等只看字段,不看身份;repr 可读,可进集合去重
class Money:
    def __init__(self, cents):
        self.cents = cents

    def __eq__(self, other):
        return isinstance(other, Money) and self.cents == other.cents

    def __hash__(self):
        return hash(("Money", self.cents))   # 与 __eq__ 一致:等值必同哈希

    def __repr__(self):
        return f"Money({self.cents})"

    def __add__(self, other):
        return Money(self.cents + other.cents)

a, b = Money(950), Money(950)
print("a == b:", a == b)
print("a is b:", a is b)
print("set size:", len({a, b}))
print("repr:", repr(a), "| str:", str(a))
print("sum:", repr(a + b + Money(50)))

# 只定义 __eq__ 不定义 __hash__:实例变不可哈希,进集合直接 TypeError
class Score:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return isinstance(other, Score) and self.value == other.value

try:
    {Score(1)}
except TypeError as exc:
    print("unhashable:", exc)