=+ Python operator is syntactically correct

早过忘川 提交于 2019-12-19 05:23:24

问题


I accidentally wrote:

total_acc =+ accuracy

instead of:

total_acc += accuracy

I searched the net and could not find anything. So what happened, why does Python think I mean what I am typing?

Computers trust us too much. :)


回答1:


This is the same as if you were to do like total_acc = -accuracy, except positive instead of negative. It basically is the same as total_acc = accuracy though, as adding a + before a value does not change it.

This is called an unary operator as there is only one argument (ex: +a) instead of two (ex: a+b).

This link explains it a little more.




回答2:


If you are interested in catching this type of errors early, you can do that with static code analysis. For example, flake8:

$ cat test.py
total_acc = 0
accuracy = 10

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

In this case, it is complaining about the extra space after the +, thinking that you actually meant total_acc = +accuracy. This would have helped you to discover the problem earlier.

FYI, pylint would catch that too.




回答3:


It thinks you're doing total_acc = +accuracy, which sets total_acc equal to accuracy. + before a variable without another value causes the variable's __pos__ method to be called. For most types, this is a nop, but there are certain types, e.g. Decimal that implement __pos__.



来源:https://stackoverflow.com/questions/35231789/python-operator-is-syntactically-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!