简体   繁体   English

高阶函数python演练

[英]higher order function python walkthrough

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)

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? 我在pythontutor.com上使用了此代码以更好地理解高阶函数,但是我很难理解为什么将步骤8中的new_fact(2)映射为已跟踪? In other words, how does the traced function know the argument is 2? 换句话说,被跟踪的函数如何知道参数为2?

In Python, functions are objects too. 在Python中,函数也是对象。 When you call the tracer() function, it returns the nested traced() function; 当您调用tracer()函数时,它将返回嵌套的traced()函数。 it is in fact creating a new copy of that function: 实际上是在创建该函数的新副本:

return traced

You stored that returned function object in new_fact , then called it: 您将返回的函数对象存储在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

You can do this with any function; 您可以使用任何功能执行此操作; store a reference to a function in another name: 用另一个名称存储对函数的引用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM