总是在作业之前先评估作业的右侧吗? [英] Is the right-hand side of an assignment always evaluated before the assignment?

查看:61
本文介绍了总是在作业之前先评估作业的右侧吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个代码段.

x = {}
x[1] = len(x)

print x
{1: 0}

这个定义得好吗?也就是说,x == {1: 1}可以代替吗?

Is this well defined? That is, could x == {1: 1} instead?

因为我记得C ++ '98中的等效程序(如果使用std::map)具有不确定的行为.用VS编译器和G ++编译时,程序的输出是不同的.

Because I remember that an equivalent program in C++ '98 (if we use std::map) has undefined behaviour. The output of the program was different when compiled with VS compiler and G++.

推荐答案

正如我在评论中提到的,该测试用例可以简化为:

As I mentioned in a comment, this test case can be reduced to:

x = {}
x[1] = len(x)

问题就变成了x[1] == 0还是x[1] == 1?

Python从左到右计算表达式.请注意,在评估作业时,右侧的评估先于左侧的评估.

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

在以下几行中,将按后缀的算术顺序对表达式求值:

In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

expr3, expr4 = expr1, expr2

因此...

len(x)在我们执行x[1]之前将被完全计算,因此x[1] == 0且定义明确.

Therefore...

len(x) will be fully computed before we do x[1], so x[1] == 0 and this is well defined.

这篇关于总是在作业之前先评估作业的右侧吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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