Is it possible to overload ++ operators in Python?
Nope, it is not possible to overload the unary ++ operator, because it is not an operator at all in Python.
Only (a subset of) the operators that are allowed by the Python syntax (those operators that already have one or more uses in the language) may be overloaded.
These are valid Python operators, and this page lists the methods that you can define to overload them (the ones with two leading and trailing underscores).
Instead of i++ as commonly used in other languages, in Python one writes i += 1.
In python the + sign needs an operand to its right. It may also have an operand to its left, in which case it will be interpreted as a binary instead of a unary operator. +5, ++5, ..., ++++++5 are all valid Python expressions (all evaluating to 5), as are 7 + 5, 7 ++ 5, ..., 7 ++++++++ 5 (all evaluating to 7 + (+...+5) = 12). 5+ is not valid Python. See also this question.
Alternative idea: Depending on what you actually wanted to use the ++ operator for, you may want to consider overloading the unary (prefix) plus operator. Note, thought, that this may lead to some odd looking code. Other people looking at your code would probably assume it's a no-op and be confused.
There is no ++
operator in Python (nor '--'). Incrementing is usually done with the +=
operator instead.
Well, the ++ operator doesn't exist in Python, so you really can't overload it.
What happens when you do something like:
1 ++ 2
is actually
1 + (+2)
Everyone makes good points, I'd just like to clear up one other thing. Open up a Python interpreter and check this out:
>>> i = 1
>>> ++i
1
>>> i
1
There is no ++ (or --) operator in Python. The reason it behaves as it did (instead of a syntax error) is that + and - are valid unary operators, acting basically like a sign would on digits. You can think of ++i
as a "+(+i)", and --i
as "-(-i)". Expecting ++i
to work like in any other language leads to absolutely insidious bug-hunts. C programmers: ye be warned.
A straight i++
or i--
does fail adequately, for what it's worth.
You could hack it, though this introduces some undesirable consequences:
class myint_plus:
def __init__(self,myint_instance):
self.myint_instance = myint_instance
def __pos__(self):
self.myint_instance.i += 1
return self.myint_instance
class myint:
def __init__(self,i):
self.i = i
def __pos__(self):
return myint_plus(self)
def __repr__(self):
return self.i.__repr__()
x = myint(1)
print x
++x
print x
the output is:
1
2