class cachedict(dict): def __init__(self, factory): self.factory = factory def __missing__(self, key): value = self[key] = self.factory(key) return value
d = cachedict(lambda x: x ** 2) print d[2] # 4
No comments:
Post a Comment