双下划线方法
Python 有一些用双下划线包起来的特殊方法名,口头上叫 dunder 方法。你已经见过 __init__。其他的让你的对象能自然地配合打印、相等比较和排序这些内置操作。
打印:__str__ 和 __repr__
__str__ 控制 print() 和 str() 显示的内容。__repr__ 是面向开发者的版本,用在交互式环境和列表里面。好习惯是至少定义其中一个。
class Money:
def __init__(self, cents):
self.cents = cents
def __str__(self):
return f"${self.cents / 100:.2f}"
def __repr__(self):
return f"Money({self.cents})"
m = Money(150)
print(m) # $1.50
print(repr(m)) # Money(150)相等:__eq__
默认情况下,只有当两个对象确实是同一个对象时它们才相等。__eq__(self, other) 让你改为按值比较。
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2) == Point(1, 2)) # True__eq__ 附带一个坑:一旦你定义了它,Python 就会把 __hash__ 设为 None,于是你的对象变得不可哈希。如果之后把它放进 set 或用作 dict 的键,就会得到 TypeError: unhashable type: 'Point'。原因是 Python 依赖的一条规则:相等的对象必须有相同的哈希值,所以一旦你重新定义了相等,它就要你有意地重新开启哈希。如果你需要,就添加一个用你比较的同样字段构建的 __hash__,或者用冻结的 dataclass(在 @dataclass 一课里讲),它会替你把两者都写好。
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y)) # same fields as __eq__
print(len({Point(1, 2), Point(1, 2)})) # 1, and no TypeError排序:__lt__
__lt__(self, other) 定义小于的规则,有了它 sorted() 就能给你的对象排序。
class Score:
def __init__(self, points):
self.points = points
def __lt__(self, other):
return self.points < other.points
def __repr__(self):
return f"Score({self.points})"
print(sorted([Score(3), Score(1), Score(2)]))
# [Score(1), Score(2), Score(3)]定义一个类 Temp,在 __init__ 里保存 self.degrees。添加 __str__,返回像 "20C" 这样的字符串(数字后面跟 C);添加 __eq__,让度数相同时两个温度相等;添加 __lt__,按 degrees 比较,这样温度列表就能排序。
这个练习即将开放
完成它前面的那一课,这一课就会解锁。整门课程免费,无需账号,而且你现在就可以阅读这节课。
这个浏览器屏蔽了 learn.floati.life 的 Cookie,所以你在这里完成的课程无法按顺序打开。请允许这个网站使用 Cookie,然后重新加载。