为什么"**"绑定比否定更紧密? [英] Why does "**" bind more tightly than negation?
问题描述
我只是被以下情况所困扰:
I was just bitten by the following scenario:
>>> -1 ** 2
-1
现在,深入研究Python文档,很明显,这是故意的行为,但是为什么?我没有使用任何其他具有内置运算符功能的语言,但是没有尽可能严格地限制一元求反对我来说似乎是违反直觉的.
Now, digging through the Python docs, it's clear that this is intended behavior, but why? I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.
是否有这样做的理由?具有操作符的其他语言的行为是否类似?
Is there a reason it was done this way? Do other languages with power operators behave similarly?
推荐答案
该行为与数学公式中的行为相同,因此我不确定问题出在哪里,或者为什么它违反直觉.您能解释一下您在哪里看到了不同的东西吗? "**"总是绑定多于-":-x ^ 2与(-x)^ 2不同
That behaviour is the same as in math formulas, so I am not sure what the problem is, or why it is counter-intuitive. Can you explain where have you seen something different? "**" always bind more than "-": -x^2 is not the same as (-x)^2
只需使用(-1)** 2,就像在数学中一样.
Just use (-1) ** 2, exactly as you'd do in math.
这篇关于为什么"**"绑定比否定更紧密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!