带整数的Python __add__魔术方法

问题描述 投票:1回答:3

当我练习时:

>>> "a".__add__("b")
'ab'

正在运行。但这

>>> 1.__add__(2)
SyntaxError: invalid syntax

不起作用。这正在工作:

>>> 1 .__add__(2) # notice that space after 1
3

这里发生了什么?它与变量命名规则有关,并且python认为我不使用空间时正在尝试创建变量吗?

python syntax int add magic-methods
3个回答
0
投票

Python词法分析器尝试将整数后跟点解释为浮点数。为了避免这种歧义,您必须添加一个额外的空间。

为了进行比较,相同的代码在double上没有问题:

>>> 4.23.__add__(2)
6.23

如果将int放在括号中也可以使用:

>>> (5).__add__(4)
9 

0
投票

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`照常做)。


0
投票

[当您使用(here,时,解释器认为您已开始写浮点数(您可以在IDE中(至少Pycharm)看到点是蓝色,而不是白色)。空格告诉它将is a valid number, then视为一个完整的数字。 1.也可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.