假设您有以下代码。
def square(x):
print ("Just before square returns")
for k in dir():
print ("{0} -------> {1}".format(k, eval(k)))
return x*x
def cube(x):
print ("Just before cube returns")
for k in dir():
print ("{0} -------> {1}".format(k, eval(k)))
return x*x*x
x = 5
print ("cube(square({0})) = {1}".format(x, cube(square(x))))
print ("Just before main returns")
for k in dir():
print ("{0} -------> {1}".format(k, eval(k)))
运行此代码会显示以下内容
Just before square returns
x -------> 5
Just before cube returns
x -------> 25
cube(square(5)) = 15625
Just before main returns
__builtins__ -------> <module 'builtins' (built-in)>
__cached__ -------> None
__doc__ -------> None
__file__ -------> exampleOne.py
__name__ -------> __main__
__package__ -------> None
cube -------> <function cube at 0x1037b78>
square -------> <function square at 0x1037af0>
x -------> 5
我们很困惑。square 函数是否首先被压入堆栈并计算其返回值并将其传递给 cube 函数?另一种可能是先调用cube函数,然后在解析参数的过程中,必须调用square函数。你能告诉我们什么?这取决于编译器或语言吗?