class memoized(object): '''Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). ''' def __init__(self, func): self.func = func self.cache = 0 def __call__(self, *args): value = self.func(*args) self.cache += 1 return value def quantos(self): return self.cache @memoized def fibonacci(n): if n in (0, 1): return n return fibonacci(n-1) + fibonacci(n-2)