It's just equal
5 - (+(-(+(-(+2)))))
where all + and - outside the first are unary operators. For numbers, +returns the operand unchanged. But its value can be redefined using a special method __pos__on your own classes.
, , ( ), __neg__ / __pos__.
, C-like pre-increment -- ++. .
class IncrementableInteger(object):
def __init__(self, val=0):
self.val = val
def __pos__(self):
class PlusOne:
def __pos__(_self):
self.val += 1
return PlusOne()
def __neg__(self):
class MinusOne:
def __neg__(_self):
self.val -= 1
return MinusOne()
def __str__(self):
return str(self.val)
def __repr__(self):
return repr(self.val)
:
>>> IncrementableInteger(4)
4
>>> v=_
>>> ++v
>>> v
5