Python重载不存在的运算符,为什么?

在搞乱重载运算符和命名元组的时候,我偶然发现了一些奇怪的行为,无论出于某种原因:

https://repl.it/repls/RemorsefulFlawlessAfricanwildcat

import collections, math

Point = collections.namedtuple("Point", ["x", "y"])
Point.__floor__ = lambda self: Point(int(math.floor(self.x)), int(math.floor(self.y)))
print(math.floor(Point(1.4, -5.9)))
#prints: Point(x=1, y=-6)

有没有人对此有任何见解?它为什么有效?
如果我删除Point .__ floor__线,它就不起作用.

数学包是否在某处定义了__floor__运算符?
要么
Python解析Point .__ XXX__以提取XXX并与作用于参数的事物(函数/运算符)的名称进行比较吗?

我很困惑,可能是因为我不知道这些东西究竟是如何工作的.

最佳答案 从文档(强调我的):

math.floor(x)

Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__(), which should return an Integral value.

点赞