=+ Python 运算符在语法上是正确的

=+ Python operator is syntactically correct

我不小心写了:

total_acc =+ accuracy

而不是:

total_acc += accuracy

我在网上搜索了一下,没找到anything。那么发生了什么,为什么 Python 认为我的意思是我输入的内容?

计算机太信任我们了。 :)

这与您要像 total_acc = -accuracy 一样,除了正面而不是负面。它基本上与 total_acc = accuracy 相同,因为在值前添加 + 不会改变它。

这称为一元运算符,因为只有一个参数(例如:+a)而不是两个(例如:a+b)。

This link再解释一下。

它认为您在做 total_acc = +accuracy,这会将 total_acc 设置为 accuracy+ 在没有另一个值的变量之前导致实现 __pos__.

的变量的 __pos__ method to be called. For most types, this is a nop, but there are certain types, e.g. Decimal

如果您有兴趣尽早发现此类错误,可以使用静态代码分析 来实现。例如,flake8:

$ cat test.py
total_acc = 0
accuracy = 10

total_acc =+ accuracy
$ flake8 test.py
test.py:4:12: E225 missing whitespace around operator

在这种情况下,它抱怨 + 之后的额外 space,认为您实际上是指 total_acc = +accuracy。这样可以帮助您更早地发现问题。

仅供参考,pylint 也会捕捉到。