高阶函数python演练 [英] higher order function python walkthrough

查看:75
本文介绍了高阶函数python演练的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?换句话说,被跟踪的函数如何知道参数为2?

I used this code on pythontutor.com to better understand higher order functions, but i'm having difficulty understanding why new_fact(2) in step 8 is mapped to traced? In other words, how does the traced function know the argument is 2?

推荐答案

在Python中,函数也是对象.当您调用tracer()函数时,它将返回嵌套的traced()函数;实际上是在创建该函数的新副本:

In Python, functions are objects too. When you call the tracer() function, it returns the nested traced() function; it is in fact creating a new copy of that function:

return traced

您将返回的函数对象存储在new_fact中,然后将其命名为:

You stored that returned function object in new_fact, then called it:

>>> 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

您可以使用任何功能执行此操作;用另一个名称存储对函数的引用:

You can do this with any function; store a reference to a function in another name:

>>> def foo(): print 'foo'
... 
>>> bar = foo
>>> bar()
foo

这篇关于高阶函数python演练的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆