Python对函数参数和操作数求值的顺序是确定性的吗(+在何处记载)? [英] Is Python's order of evaluation of function arguments and operands deterministic (+ where is it documented)?

查看:74
本文介绍了Python对函数参数和操作数求值的顺序是确定性的吗(+在何处记载)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C不能不能保证任何评估订单,所以类似可以按任意顺序执行g1()g2()g3()g4()(尽管f()将在所有它们之后执行)

C doesn't guarantee any evaluation order so a statement like f(g1()+g2(), g3(), g4()) might execute g1(), g2(), g3(), and g4() in any order (although f() would be executed after all of them)

Python呢?我对Python 2.7的实验表明,它似乎是从左到右的评估顺序,但我想知道是否指定了这种情况.

测试程序:

def somefunc(prolog, epilog):
    print prolog
    def f(a, b, *args):
        print epilog
    return f        

def f(text):
    print text
    return 1

somefunc('f1','f2')(f('hey'),f('ho'),f('hahaha'),f('tweedledee')+f('tweedledum'))

可打印

f1
hey
ho
hahaha
tweedledee
tweedledum
f2

推荐答案

是的,除作业外,可以保证从左到右的评估顺序.在此处进行了记录( py2

Yes, left to right evaluation order is guaranteed, with the exception of assignments. That's documented here (py2, py3):

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:

expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2

如果该语言没有对此做出选择,则对一个参数的求值可能会使另一个参数变异并导致未指定的行为,因此Python的所有实现都必须遵循此规范.

If the language were not making some choice about this, the evaluation of one argument could mutate another argument and result in unspecified behaviour, so all implementations of Python must follow this spec.

这篇关于Python对函数参数和操作数求值的顺序是确定性的吗(+在何处记载)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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