3

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.

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I found it myself just before I read your answer. I looked in docs.python.org/3/reference/datamodel.html#data-model , but couldn't find it. Later found it where you linked. In hindsight, I should have checked math.floor documentation, but I thought all __ XXX __ are listed in the datamodel.html page.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.