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

Possible duplicate:
access python-style literal methods
Is an integer literal an object in Python?

In python it is possible, and sometimes ordinary, to call methods or look for attributes directly in literals:

>>> "-".join("abc") 'abc' >>> {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 for whole objects:

 >>> 3.__add__(42) File "<stdin>", line 1 3.__add__(42) ^ SyntaxError: invalid syntax 

Why not?

+4
source share
1 answer

As usual, when I start introducing the question about stack overflow, I find the likely answer myself when I study it. Well, today I post the question anyway, as well as what I consider the answer:

It does not work for integers because . interpreted by the parser as a decimal point. The float example works because the parser knows that the second period must be a search attribute - in this case there is no ambiguity.

+8
source

Source: https://habr.com/ru/post/1441279/


All Articles