当我练习时:
>>> "a".__add__("b")
'ab'
正在运行。但这
>>> 1.__add__(2)
SyntaxError: invalid syntax
不起作用。这正在工作:
>>> 1 .__add__(2) # notice that space after 1
3
这里发生了什么?它与变量命名规则有关,并且python认为我不使用空间时正在尝试创建变量吗?
Python词法分析器尝试将整数后跟点解释为浮点数。为了避免这种歧义,您必须添加一个额外的空间。
为了进行比较,相同的代码在double上没有问题:
>>> 4.23.__add__(2)
6.23
如果将int放在括号中也可以使用:
>>> (5).__add__(4)
9
Python解析器特意保持愚蠢而简单。当它看到1.
时,会认为您在浮点数的中间,并且1._
不是有效的数字(或更正确地说,1.
是有效的浮点,并且您不能在[ C0]:“ a” 添加(“ b”)_
。is also an error). Thus, anything that makes it clear that
(1)。添加(2)is not a part of the number helps: having a space before the dot, as you discovered (since space is not found in numbers, Python abandons the idea of a float and goes with integral syntax). Parentheses would also help:
1 .. 添加(2)[ C0] 1. . Adding another dot does as well:
。add`照常做)。
[当您使用(here,
时,解释器认为您已开始写浮点数(您可以在IDE中(至少Pycharm)看到点是蓝色,而不是白色)。空格告诉它将is a valid number, then
视为一个完整的数字。 1.
也可以解决问题。