此笔记解释python中call的执行顺序问题
例子来源于HW01的Q4
Q4: If Function vs Statement
Let’s try to write a function that does the same thing as an if statement.
def if_function(condition, true_result, false_result):
"""Return true_result if condition is a true value, and
false_result otherwise.
>>> if_function(True, 2, 3)
2
>>> if_function(False, 2, 3)
3
>>> if_function(3==2, 3+2, 3-2)
1
>>> if_function(3>2, 3+2, 3-2)
5
"""
if condition:
return true_result
else:
return false_result
Despite the doctests above, this function actually does not do the same thing as an if statement in all cases. To prove this fact, write functions c, t, and f such that with_if_statement prints the number 2, but with_if_function prints both 1 and 2.
def with_if_statement():
"""
>>> result = with_if_statement()
2
>>> print(result)
None
"""
if c():
return t()
else:
return f()
def with_if_function():
"""
>>> result = with_if_function()
1
2
>>> print(result)
None
"""
return if_function(c(), t(), f())
def c():
"*** YOUR CODE HERE ***"
def t():
"*** YOUR CODE HERE ***"
def f():
"*** YOUR CODE HERE ***"
答案:
def c():
"*** YOUR CODE HERE ***"
return 0
def t():
"*** YOUR CODE HERE ***"
return print(5)
def f():
"*** YOUR CODE HERE ***"
return print(6)
可以看到,在运行with_if_function中,我们call了if_function. call expression需要处理operator和operand. 而当operand需要计算(call)的时候,很自然的想法是我们先计算完所有operand(此例子就是call了函数c,t,f),然后再创建operator的local frame。因为如果先创建operator的local frame再计算operand,local frame里面的值就需要实时改动,和operand的计算有复杂的关系。这样子就没有全部计算完然后一次性填入到local frame简单效率。这也就解释了为什么会打印5和6,因为我们先call了c,t和f,再运行了if_function。而如果直接建立if_function的local frame并顺序运行,我们再call了c之后,就会返回false_result并结束程序了,并不会运行t从而打印6。此例子展现了python运行函数的原理,如果函数A的参数是别的函数或需要计算,我们会先计算它们再运行函数A,编程时需要注意这些计算产生的副作用,如print等