扩展赋值的Python运算符优先级 [英] Python operator precedence with augmented assignment

查看:108
本文介绍了扩展赋值的Python运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎这个问题只针对Java回答,但我想知道它在Python中是如何工作的.这些都一样吗?

It seems this question only answered for Java but I would like to know how it works in Python. So are these the same?

a += b / 2

a += (b / 2)

推荐答案

是的,它们是相同的. Python的增强分配不是表达式,它是一条语句,并且不在表达式优先级规则中发挥作用. +=不是运算符,而是扩展的赋值语句语法的一部分.

Yes, those are the same. Python's augmented assignment is not an expression, it is a statement, and doesn't play in expression precedence rules. += is not an operator, and instead it's part of the augmented assignment statement syntax.

因此,+= 右侧的所有都是表达式,而+=本身不是,因此分配将始终在最后处理.

So everything to the right of the += is an expression, but += itself is not, so the assignment will always be handled last.

并且因为(增强的)赋值不是表达式,所以它也不能产生在周围表达式中使用的值.没有(a += b) / 2,那是语法错误,当然也没有if (a += b / 2):或其他类似的恶作剧.

And because (augmented) assignment is not an expression, it can't produce a value to use in a surrounding expression either. There is no (a += b) / 2, that'd be a syntax error, and certainly no if (a += b / 2): or other such shenanigans.

有关增强的赋值语句,请参见参考文档 ,其语法为:

See the reference documentation on Augmented assignment statements, which states the grammar is:

augmented_assignment_stmt ::=  augtarget augop (expression_list | yield_expression)
augtarget                 ::=  identifier | attributeref | subscription | slicing
augop                     ::=  "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
                           | ">>=" | "<<=" | "&=" | "^=" | "|="

因此,augop是语句语法的一部分,并且仅后面的部分是表达式(具体来说,是expression_listyield_expression语法规则).

So the augop is part of the statement syntax, and only the part following is an expression (specifically, either a expression_list or yield_expression grammar rule).

此外,说明显示:

扩充赋值评估目标(与普通赋值语句不同,不能解压缩)和表达式列表,对两个操作数执行特定于赋值类型的二进制运算,并将结果赋值给原始目标.该目标仅评估一次.

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

因此,首先处理augtarget部分,然后处理表达式列表(或yield表达式),然后扩展分配应用运算符并分配回结果.

So the augtarget part is handled first, the expression list (or yield expression) is handled second, and then the augmented assignment applies the operator and assigns back the result.

此外,表达式参考文档包含优先级表,但该表不包含赋值(增值或其他形式),只是因为赋值不是表达式而是语句.

Furthermore, the expressions reference documentation does include a precedence table, but that table doesn't include assignments (augmented or otherwise), simply because assignments are not expressions but statements.

这篇关于扩展赋值的Python运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆