实现说明
底层就是类 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)