使用和实现装饰器

使用装饰器格式为:@+装饰器名称;实现一个装饰器首先要理解闭包的思想,如下例子:实现了斐波那契数列

def fb(n):

    if n <= 1:
        return 1

    return fb(n-1) + fb(n-2)

以上实现方式每次都要计算元素,非常耗时和消耗内存,以下增加了一个缓存的字典,从缓存中读取大大提高了运算的速度


def fb(n ,cahe = None):
    
    if cahe is None:
        cahe = {}

    if n in cahe:
        return cahe[n]

    if n <= 1:
        return 1

    cahe[n] = fb(n-1) + fb(n-2)
    return cahe[n]

如果实现多种不同的算法,为了节省运算时间,每个算法都要添加一个缓存,会出现很多的重复代码,所以使用闭包的思想实现一个装饰器,如下

'''装饰器使用了闭包的思想'''
def memo(fun):

    ache = {}

    def wrap(*args):

        if args not in ache:
            ache[args] = fun(*args)
        return ache[args]
    return wrap

@memo #@memo是 fb = memo(fb) 在python中提供的简单写法
def fb(n):

    if n <= 1:
        return 1

    return fb(n-1) + fb(n-2)

@memo
def climb(n, steps):

    count = 0
    if n == 0:
        count = 1

    elif n > 0:
        for step in steps:
            count += climb(n - step, steps)
    return count


print fb(60)

print climb(10, (1, 2, 3))
原文地址:https://www.cnblogs.com/misslin/p/6722521.html