Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python overloading non-existent operator works, why?

While messing around with overloading operators and namedtuples, I've stumbled on some weird behavior which works, for some reason or another:

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)

Does anyone have any insight into this? Why does it work?
If I remove the Point.__floor__ line, it doesn't work.


Did the math package define a __floor__ operator somewhere?
OR
Does Python parse Point.__XXX__ to extract XXX and compare with the name of the thing (function/operator) that acts on the argument?

I'm confused, probably because I don't know how exactly these things work deep down.

like image 719
Quirinus Avatar asked Jan 17 '26 13:01

Quirinus


1 Answers

From the docs (emphasis mine):

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.

like image 161
internet_user Avatar answered Jan 20 '26 02:01

internet_user