Python 对函数参数和操作数的评估顺序是否具有确定性(+ 记录在何处)? [英] Is Python's order of evaluation of function arguments and operands deterministic (+ where is it documented)?
问题描述
C 不保证任何评估顺序,所以像 f(g1()+g2(), g3(), g4())
可能会执行 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, py3):
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屋!