The Way 2 Inner Peace.


Python decorators

Qians posted @ 2012年6月24日 14:38 in python with tags python udacity , 1440 阅读

In python,a decorators starts with @,such as:

def func1():
    print "inside func1()"

It means:


Here is a useful decorator.

from functools import update_wrapper

def decorator(d):
    "Make function d a decorator: d wraps a function fn."
    def _d(fn):
        return update_wrapper(d(fn), fn)
    update_wrapper(_d, d)
    return _d

def memo(f):
    """Decorator that caches the return value for each call to f(args).
    Then when called again with same args, we can just look it up."""
    cache = {}
    def _f(*args):
            return cache[args]
        except KeyError:
            cache[args] = result = f(*args)
            return result
        except TypeError:
            # some element of args can't be a dict key
            return f(*args)
    _f.cache = cache
    return _f

Then,implement it on fib

def fib(n):
    if n == 0 or n == 1:
        return 1
        return fib(n-1) + fib(n-2)

print fib(100)


udacity cs212 unit3 note

udacity cs212 unit5 note

Plux 说:
2012年6月25日 20:39


登录 *

loading captcha image...
or Ctrl+Enter