Python doesn't support C-style ++a
increment but, to my surprise, it doesn't complain either leading to me being temporarily baffled as to why my loop wasn't working.
Trying a few things (having first initialised with a=0
) I find that a++
and a--
produce a syntax error, but ++a
doesn't. While --a
produces a syntax error in Python 3.3 but not in Python 2.7.
What's going on? Why doesn't ++a
give an error? Why does --a
not give an error in 2.7 but does give an error in 3.3?
Take a look at this console session:
>>> a = 10
>>> ++a
10
>>> +a
10
>>> -a
-10
>>> --a
10
Basically, ++a == +(+(a))
, and --a == -(-(a))
. This one's to hit the concept home (and for fun):
>>> ++++++++++a
10
The following code sample serves no purpose other than to show you how much fun python is:
>>> +-+-+a
10
With something like this, you can make ASCII art that runs.
If you want to increment you do it like so: a += 1
. And --a
works in Python 2 and 3.
Short answer: it calls the __pos__
method twice. Consider for instance:
>>> class A(object):
... def __init__(self, x):
... self.x = x
... def __pos__(self):
... return A(2 * self.x)
... def __repr__(self):
... return 'A(%s)' % self.x
...
>>> a = A(1)
>>> a
A(1)
>>> +a
A(2)
>>> ++a
A(4)
>>> +++a
A(8)
For integers, as +x
returns x
, it does basically nothing.
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