Python 函数对象有一个名为的属性字典,该字典func_dict
从函数外部可见并且是可变的,但在调用函数时不会修改。(我从昨天提出的问题的答案中了解到这一点(#1753232):谢谢!)我正在阅读代码(在http://pythonprogramming.jottit.com/functional_programming),它记住了斐波那契数的计算并想,“为什么不使用该func_dict
属性进行记忆?” 它起作用了(见下文;输出在代码的末尾。)。这有点像有一个可用的类属性,但在对象之外有初始化代码(在这种情况下,不是一个类,而是一个函数)。
我想知道使用此属性可以完成哪些类似(或不同)的技巧?
def fib(n):
if n in fib.cache:
print "found fib.cache[%d] = %d: " %(n, fib.cache[n])
return fib.cache[n]
else:
print "fib.cache[%d] = fib(%d) + fib(%d)" % (n, n-1, n-2)
fib.cache[n] = fib(n-1) + fib(n-2)
print "modified fib.cache: ", fib.cache
return fib.cache[n]
fib.cache = {0:0, 1:1}
for x in range(7):
print "==================>", x
print fib( x)
"""
==================> 0
found fib.cache[0] = 0:
0
==================> 1
found fib.cache[1] = 1:
1
==================> 2
fib.cache[2] = fib(1) + fib(0)
found fib.cache[1] = 1:
found fib.cache[0] = 0:
modified fib.cache: {0: 0, 1: 1, 2: 1}
1
==================> 3
fib.cache[3] = fib(2) + fib(1)
found fib.cache[2] = 1:
found fib.cache[1] = 1:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2}
2
==================> 4
fib.cache[4] = fib(3) + fib(2)
found fib.cache[3] = 2:
found fib.cache[2] = 1:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
3
==================> 5
fib.cache[5] = fib(4) + fib(3)
found fib.cache[4] = 3:
found fib.cache[3] = 2:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5}
5
==================> 6
fib.cache[6] = fib(5) + fib(4)
found fib.cache[5] = 5:
found fib.cache[4] = 3:
modified fib.cache: {0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8}
8
"""