Python 重载不存在的运算符有效,为什么?
Python overloading non-existent operator works, why?
在处理重载运算符和命名元组时,出于某种原因,我偶然发现了一些奇怪的行为:
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
并与作用于参数的事物的名称 (function/operator) 进行比较?
我很困惑,可能是因为我不知道这些东西到底是如何运作的。
来自文档(强调我的):
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.
在处理重载运算符和命名元组时,出于某种原因,我偶然发现了一些奇怪的行为:
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
并与作用于参数的事物的名称 (function/operator) 进行比较?
我很困惑,可能是因为我不知道这些东西到底是如何运作的。
来自文档(强调我的):
math.floor(x)
Return the floor of
x
, the largest integer less than or equal to x. If x is not a float, delegates tox.__floor__()
, which should return an Integral value.