Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I call methods directly on int objects? [duplicate]

Tags:

python

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?

like image 309
Lauritz V. Thaulow Avatar asked Feb 19 '23 18:02

Lauritz V. Thaulow


1 Answers

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.

like image 91
Lauritz V. Thaulow Avatar answered Feb 27 '23 14:02

Lauritz V. Thaulow