Python3 int.__sizeof__() 产生语法错误

W4t*_*ind 1 python oop integer

以下代码产生语法错误。有谁知道为什么在使用对象属性时会导致语法错误?

Python 3.7.4 (default, Jul 27 2020, 09:35:23) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>1.__sizeof__()
  File "<stdin
    1.__sizeof__()
               ^
SyntaxError: invalid syntax
>>>
Run Code Online (Sandbox Code Playgroud)

che*_*ner 6

词法分析器是 greedy 的,因此它识别1.__sizeof__()float文字1.后跟标识符__sizeof__,而不是int文字后跟.运算符。

$ python -m tokenize <<< "1.__sizeof__()"
1,0-1,2:            NUMBER         '1.'
1,2-1,12:           NAME           '__sizeof__'
1,12-1,13:          OP             '('
1,13-1,14:          OP             ')'
1,14-1,15:          NEWLINE        '\n'
2,0-2,0:            ENDMARKER      ''
Run Code Online (Sandbox Code Playgroud)

使用括号覆盖辅助词法分析器:

>>> (1).__sizeof__()
28
Run Code Online (Sandbox Code Playgroud)

  • @VisioN:但这给了你一个浮点数而不是一个整数,这很重要。 (2认同)