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)映射到traced?换句话说,traced函数如何知道参数是2
发布于 2013-08-17 09:36:06
在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()
foohttps://stackoverflow.com/questions/18287260
复制相似问题