Increment with __pos__
In Python, there is no increment operation ++
like in C-like languages, so x += 1
is used instead. However, the expression ++x
is valid code (but not x++
), as it's just two unary addition operators.
When applying a unary plus to an object, the magic method __pos__
is called, so the expression ++x
can be understood as x.__pos__().__pos__()
. Knowing this, we can implement a class that represents a number and supports increment behavior.
The code in the image might seem a bit complex at first, but it's better to trace the logic and understand how the __pos__
method works. If all other necessary magic methods are implemented, a fully functional number class can be created, but it's better not to use such tricks in production code.
Page of .
Leave a comment
You must be logged in to leave a comment.
Log in or
sign up to join the discussion.
Comments (0)