Python重载不存在的操作符可以工作,为什么?

2024-04-19 17:03:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在处理重载操作符和namedtuples时,我偶然发现了一些奇怪的行为,出于某种原因:

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__来提取{}并与作用于参数的事物(函数/运算符)的名称进行比较?在

我很困惑,可能是因为我不知道这些东西到底是怎么运作的。在


Tags: httpsimportselfit运算符mathreplnamedtuple
1条回答
网友
1楼 · 发布于 2024-04-19 17:03:49

从文件(重点是我的):

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.

相关问题 更多 >