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

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

问题描述

这是一个代码片段.

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?

The question then becomes, is x[1] == 0, or is 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天全站免登陆