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.
Code
# 值对象:相等只看字段,不看身份;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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.