def tracer(fn):
def traced(x):
print('Calling',fn,'(',x,')')
result=fn(x)
print('Got',result,'from',fn,'(',x,')')
return result
return traced
def fact(n):
if n ==0:
return 1
return n * fact(n-1)
new_fact = tracer(fact)
new_fact(2)
我在pythontutor.com上使用此代码来更好地理解高阶函数,但是我很难理解为什么步骤8中的new_fact(2)被映射到跟踪?换句话说,跟踪函数如何知道参数是2?
答案 0 :(得分:4)
在Python中,函数也是对象。当您调用tracer()
函数时,它将返回嵌套的traced()
函数;它实际上是在创建该函数的新副本:
return traced
您将返回的函数对象存储在new_fact
中,然后调用它:
>>> tracer(fact)
<function traced at 0x10644c320>
>>> new_fact = tracer(fact)
>>> new_fact
<function traced at 0x10644c398>
>>> new_fact(2)
('Calling', <function fact at 0x10644c230>, '(', 2, ')')
('Got', 2, 'from', <function fact at 0x10644c230>, '(', 2, ')')
2
你可以用任何功能做到这一点;以另一个名称存储对函数的引用:
>>> def foo(): print 'foo'
...
>>> bar = foo
>>> bar()
foo