mar*_*ion 3 python arguments function
我在Python书中看到了这个例子,它展示了如何使用函数作为另一个函数的参数:
def diff2(f, x, h=1E-6):
r = (f(x-h) - 2*f(x) + f(x+h))/float(h*h)
return r
def g(t):
return t**(-6)
t = 1.2
d2g = diff2(g, t)
print d2g
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果没有为函数g提供参数,这个脚本如何工作?有问题的一行是:
d2g = diff2(g,t)
Run Code Online (Sandbox Code Playgroud)
不应该这样做:
d2g = diff2(g(t), t)
Run Code Online (Sandbox Code Playgroud)
g
作为参数传递给diff2
.在diff2
,该参数被调用f
,因此diff2
名称内部f
引用该函数g
.当diff2
调用f(x-h)
(以及其他调用它)时,它正在调用g
并提供参数.
换句话说,当你这样做时diff2(g, t)
,你就diff2
知道这g
是要调用的函数.参数g
提供在diff2
:
f(x-h) # calls g with x-h as the argument
f(x) # calls g with x as the argument
f(x+h) # calls g with x+h as the argument
Run Code Online (Sandbox Code Playgroud)
如果你打电话diff2(g(t), t)
,你会传递结果的g(1.2)
作为参数. g
将在调用之前调用diff2
,diff2
然后在尝试调用时失败f
,因为f
它将是一个数字(值g(1.2)
)而不是函数.