为什么这行代码以这种方式工作?

时间:2012-03-13 21:54:11

标签: python

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)



print "Here is a puzzle."

# why does the line of code below work in this way?
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

注释下面的第一行是调用函数除法。我好奇,为什么这样做?是因为python实际上理解操作的顺序还是因为这条线的链结构?

4 个答案:

答案 0 :(得分:3)

在调用函数之前,Python必须评估传递给该函数的参数。 (没有其他选择 - 参数的值只有在已知的情况下才能传递。)

递归地应用这个原则,唯一的选择是首先调用divide() - 在此之前,没有其他函数的参数是已知的。

答案 1 :(得分:2)

想一想。当您不知道add()的结果是什么时,您会如何致电subtract()?如果您不知道subtract()的结果是什么,您会如何致电multiply()?最后,如果您不知道multiply()的结果是什么,您会如何致电divide()

与代数表示法一样,括号内的操作首先完成。如果括号内有括号,则首先执行最内层操作。它不能以任何其他方式工作。

答案 2 :(得分:1)

答案很简单 - 所有函数参数必须在调用之前进行评估才能运行。

在这种情况下:

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

要计算add(...)的值,您必须计算age

的值
subtract(height, multiply(weight, divide(iq, 2)))

要计算subtract(...)的值,您必须计算height

的值
multiply(weight, divide(iq, 2))

等等。

答案 3 :(得分:0)

Python(以及任何具有函数的语言)理解函数调用的操作顺序。

如果你有一些函数f(),g()和h(),那么像

这样的语句
f(g(h()))

需要h()的结果才能调用g(),并且在调用f()之前需要g(h())的结果。