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.
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 tox.__floor__(), which should return an Integral value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With