Python高阶函数

时间:2016-07-23 11:33:48

标签: python functional-programming

鉴于以下代码,我无法理解为什么f和fib表现不同。 这个例子来自Barkley cs61a课程

def fib(n):
    if n==1 or n==0:
        return n
    else:
        return fib(n-1) + fib(n-2)

def decor(f):
    def counted(*args):
        counted.call_count += 1
        return f(*args)
    counted.call_count = 0
    return counted

当我将代码加载到解释器中时,我得到了这个输出:

>>> fib(6)
8
>>> f = decor(fib)
>>> fib = decor(fib)
>>> # f and fib are both vars that represents a decorated fib function

>>> f(6)
8
>>> f.call_count # why 1 ???
1
>>> 
>>> fib(6)
8
>>> fib.call_count # 49 calls, that's fine
49

2 个答案:

答案 0 :(得分:2)

f.call_count为1,因为f调用fib,然后fib递归调用自身来计算结果。在整个过程中,f只被调用一次。

但是当你执行fib = decor(fib)时,你会覆盖全局范围内的fib函数,所以从fib开始,递归调用装饰< / em> fib

答案 1 :(得分:0)

您正在覆盖fib,然后f调用fib而不是自己:

def fib(n):
    if n==1 or n==0:
        return n
    else:
        print("fib is: " + repr(fib))
        return fib(n-1) + fib(n-2)

def decor(f):
    def counted(*args):
        counted.call_count += 1
        return f(*args)
    counted.call_count = 0
    return counted



f = decor(fib)
fib = decor(fib)

print("=== f ===")
print(f(6))
print(f.call_count)

print("=== fib ===")
print(fib(6))
print(fib.call_count)

当我运行它时,输出是:

=== f ===
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
8
1
=== fib ===
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
fib is: <function counted at 0x7fa844639758>
8
49

请注意,fib is始终在0x7fa844639758处发挥作用。