Value Objects: __eq__ And __hash__ Agree

Define Money-style value objects where equality compares fields: __eq__ without __hash__ makes instances unhashable, so the pair must agree.

PythonData Integrity

Code

pythonsnippet
36 lines
# 值对象:相等只看字段,不看身份;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)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

the classes Money and Score and the functions __init__, __eq__, __hash__ and __repr__ cover the runnable surface of Value Objects: eq And hash Agree.

What to watch for

  • All symbols are built into the language — there is nothing to pull in.

Putting it to use

The line that opens the logic: def __init__(self, cents)

Each run prints the 6 labeled blocks a == b:, a is b:, set size:, repr:, sum:, unhashable: in source order.

Core lines

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

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `__init__`, `__eq__`, `__hash__` at load time.