[Python] Python 2.5 __missing__()
Rob Hudson
rob at euglug.net
Fri Oct 27 08:28:26 PDT 2006
Hey, that's cool. :)
How do you know what's going to be passed to __missing__()? Is it
always the same as __call__()?
-Rob
Bob Miller wrote:
> Python 2.5 allows classes derived from dict to define a
> __missing__(self, key) method. That means that you can write a
> memoized function like this.
>
> >>> class MemoFibonacci(dict):
> ... def __missing__(self, n):
> ... self[n] = 1 if n < 2 else self[n - 1] + self[n - 2]
> ... return self[n]
> ... def __call__(self, n):
> ... return self[n]
> ...
> >>> fib = MemoFibonacci()
> >>> [fib(i) for i in range(7)]
> [1, 1, 2, 3, 5, 8, 13]
>
> Note the gratuitous use of a conditional expression too. (-:
>
More information about the Python
mailing list