简体   繁体   English

Python __add__ 带整数的魔术方法

[英]Python __add__ magic method with integers

When i am tring this:当我正在尝试这个时:

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

It is working.这是工作。 But this但是这个

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

is not working.不管用。 And this is working:这是有效的:

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

What is going here?这是怎么回事? Is it about variable naming rules and is python thinks I am trying to create variable when I am not using space?是否与变量命名规则有关,python 是否认为我在不使用空间时尝试创建变量?

Python parser is intentionally kept dumb and simple. Python 解析器故意保持简单和简单。 When it sees 1. , it thinks you are midway through a floating point number, and 1._ is not a valid number (or more correctly, 1. is a valid float, and you can't follow a value by _ : "a" __add__("b") is also an error).当它看到1.时,它认为你在一个浮点数的中间,并且1._不是一个有效的数字(或者更准确地说, 1.是一个有效的浮点数,你不能跟随一个值_"a" __add__("b")也是一个错误)。 Thus, anything that makes it clear that .因此,任何可以清楚地表明. 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).不是数字的一部分有帮助:在点之前有一个空格,正如您所发现的(因为在数字中找不到空格,Python 放弃了浮点数的想法并采用整数语法)。 Parentheses would also help: (1).__add__(2) .括号也有帮助: (1).__add__(2) Adding another dot does as well: 1..__add__(2) (here, 1. is a valid number, then .__add__ does the usual thing).添加另一个点也可以: 1..__add__(2) (这里, 1.是一个有效数字,然后.__add__做通常的事情)。

The python lexical parser tries to interpret an integer followed by a dot as a floating point number. python 词法解析器尝试将 integer 后跟一个点解释为浮点数。 To avoid this ambiguity, you have to add an extra space.为了避免这种歧义,您必须添加一个额外的空格。

For comparison, the same code works without problem on a double:为了比较,相同的代码在 double 上没有问题:

>>> 4.23.__add__(2)
6.23

It also works if you put the int in parentheses:如果将 int 放在括号中,它也可以:

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

When you use 1. the interpreter think you started writing float number (you can see in the IDE (atleast Pycharm) the dot is blue, not white).当您使用1.解释器认为您开始编写浮点数时(您可以在 IDE(至少 Pycharm)中看到点是蓝色的,而不是白色的)。 The space tell it to treat 1. as a complete number, 1.0 .空格告诉它将1.视为一个完整的数字1.0 1..__add__(2) will also do the trick. 1..__add__(2)也可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM