Python 2.7: Ints as Objects

How int in python avoids being an object, but still is one:

If I do the following:

>>> dir(10) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] >>> 10.__add__(20) File "<stdin>", line 1 10.__add__(20) ^ SyntaxError: invalid syntax 

If I type 10., it produces 10.0, while anything, like 10 .__ anything __, generates a syntax error. This makes sense since the float will be considered 10.5, but

  • How is this achieved / implemented?
  • how can i call int methods in int?
+5
source share
3 answers

The Python tokenizer is greedy, it always tries to match the longest token at any given position; otherwise, he might think that 10.e+123 same as (10).e + 123 .

In case of 10.__add__(20) he sees the following tokens:

 >>> tokenize.tokenize(iter(['10.__add__(20)']).next) 1,0-1,3: NUMBER '10.' 1,3-1,10: NAME '__add__' 1,10-1,11: OP '(' 1,11-1,13: NUMBER '20' 1,13-1,14: OP ')' 2,0-2,0: ENDMARKER '' 

ie,. was considered part of the literal number, for example. a float . If you copy the number ( (10).__add__(20) ), you will get:

 >>> tokenize.tokenize(iter(['(10).__add__(20)']).next) 1,0-1,1: OP '(' 1,1-1,3: NUMBER '10' 1,3-1,4: OP ')' 1,4-1,5: OP '.' 1,5-1,12: NAME '__add__' 1,12-1,13: OP '(' 1,13-1,15: NUMBER '20' 1,15-1,16: OP ')' 2,0-2,0: ENDMARKER '' 

Similarly, just adding a space between a number and a period ( 10 . ) Will work here.

Here . designated as a separate operator. If the float constant existed, then you could type:

 10..__add__(20) 

This is referred to as float literal 10. followed by . followed by __add__ identifier etc.


The stupid iter().next should be iter().__next__ in Python 3. For tokenize.tokenize , the argument readline requires a similar function; when called, it should return a program input string.

+7
source

Just use parentheses around the number:

 (10).__add__(20) 
+2
source

This is a lexical issue. You can wrap the number in brackets to access items, for example. (10).__add__(20)

The expression 10.__add__(20) parsed / lexed as (10.) __add__(20) .

+2
source

All Articles