Possible Duplicate:
accessing a python int literals methods
Integer literal is an object in Python?
In python it's possible, and sometimes even common, to call methods or look up attributes directly on literals:
>>> "-".join("abc")
'a-b-c'
>>> {1: 3, 2: 9}.pop(1)
3
>>> 3j.imag
3.0
>>> 8.0.__add__(8)
16.0
But for some reason this does not work on integer objects:
>>> 3.__add__(42)
File "<stdin>", line 1
3.__add__(42)
^
SyntaxError: invalid syntax
Why not?
As is normally the case when I start typing a Stack Overflow question, I find the likely answer myself as I'm researching it. Well, today I'm posting the question anyway, along with what I think is the answer:
It does not work for integers because the .
is interpreted as a decimal point by the parser. The float example works because the parser knows that the second period must be attribute lookup -- there is no ambiguity in this case.
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