Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer literal is an object in Python? [duplicate]

Tags:

python

syntax

Possible Duplicate:
accessing a python int literals methods

Everything in Python is an object. Even a number is an object:

>>> a=1
>>> type(a)
<class 'int'>
>>>a.real
1

I tried the following, because we should be able to access class members of an object:

>>> type(1)
<class 'int'>
>>> 1.real
  File "<stdin>", line 1
    1.real
         ^
SyntaxError: invalid syntax

Why does this not work?

like image 242
user1559873 Avatar asked Aug 03 '12 19:08

user1559873


2 Answers

Yes, an integer literal is an object in Python. To summarize, the parser needs to be able to understand it is dealing with an object of type integer, while the statement 1.real confuses the parser into thinking it has a float 1. followed by the word real, and therefore raises a syntax error.

To test this you can also try

>> (1).real
  1

as well as,

>> 1.0.real
  1.0

so in the case of 1.real python is interpreting the . as a decimal point.

Edit

BasicWolf puts it nicely too - 1. is being interpreted as the floating point representation of 1, so 1.real is equivalent to writing (1.)real - so with no attribute access operator i.e. period /full stop. Hence the syntax error.

Further edit

As mgilson alludes to in his/her comment: the parser can handle access to int's attributes and methods, but only as long the statement makes it clear that it is being given an int and not a float.

like image 78
jmetz Avatar answered Oct 21 '22 07:10

jmetz


a language is usually built in three layers.

when you provide a program to a language it first has to "read" the program. then it builds what it has read into something it can work with. and finally it runs that thing as "a program" and (hopefully) prints a result.

the problem here is that the first part of python - the part that reads programs - is confused. it's confused because it's not clever enough to know the difference between

1.234

and

1.letters

what seems to be happening is that it thinks you were trying to type a number like 1.234 but made a mistake and typed letters instead(!).

so this has nothing to do with what 1 "really is" and whether or not is it an object. all that kind of logic happens in the second and third stages i described earlier, when python tries to build and then run the program.

what you've uncovered is just a strange (but interesting!) wrinkle in how python reads programs.

[i'd call it a bug, but it's probably like this for a reason. it turns out that some things are hard for computers to read. python is probably designed so that it's easy (fast) for the computer to read programs. fixing this "bug" would probably make the part of python that reads programs slower or more complicated. so it's probably a trade-off.]

like image 43
andrew cooke Avatar answered Oct 21 '22 08:10

andrew cooke