为了说明问题,我创建了一个简单的示例:
#!/usr/bin/env python
class Person():
def __init__(self):
self.cache = {}
def get_person_age(self):
def get_age():
print "Calculating age..."
return self.age
print self.cache
return self.cache.setdefault(self.name, get_age())
def set_person(self, name, age):
self.name = name
self.age = age
p = Person()
p.set_person('andrei', 12)
for k in range(0, 5):
p.get_person_age()
我希望一旦设置了缓存,将永远不会再次调用函数 get_person_age ,但这不是真的:
$ python cache_test.py
{}
Calculating age...
{'andrei': 12}
Calculating age...
{'andrei': 12}
Calculating age...
{'andrei': 12}
Calculating age...
{'andrei': 12}
Calculating age...
函数被一次又一次地调用。怎么了?