HW1 Python中call expression的执行顺序

此笔记解释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等

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值