Possible Duplicate:
Behaviour of increment and decrement operators in Python
Completely new to python I wrote ++x thinking it would increment x. So I was wrong about that, no problem. But no syntax error either. Hence my question: what does ++x actually mean in python?
The + operator is the unary plus operator; it returns its numeric argument unchanged. So ++x is parsed as +(+(x)), and gives x unchanged (as long as x contains a number):
>>> ++5
5
>>> ++"hello"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
If + is called on an object of a user-defined class, the __pos__ special method will be called if it exists; otherwise, TypeError will be raised as above.
To confirm this we can use the ast module to show how Python parses the expression:
import ast
print(ast.dump(ast.parse('++x', mode='eval')))
Expression(body=UnaryOp(op=UAdd(), operand=UnaryOp(op=UAdd(), operand=Name(id='x', ctx=Load()))))
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