The Way 2 Inner Peace.

利用coverage测试python代码覆盖率

Python decorators

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

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

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

It means:

func1=myDecorator(func1)

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

@decorator
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):
        try:
            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

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

print fib(100)

参考:

udacity cs212 unit3 note

udacity cs212 unit5 note

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

Decorator用于测试某一个方法挺好的。

seo service UK 说:
2024年1月16日 17:25

Superb article. Thanks to this blog my expedition has actually ended.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter