python decorator

python decorator:

Memoization can be expressed naturally as a higher-order function, which can also be used as a decorator. The definition below creates a cache of previously computed results, indexed by the arguments from which they were computed. The use of a dictionary requires that the argument to the memoized function be immutable.

def memo(f):
    cache = {}
    def memoized(n):
        if n not in cache:
            cache[n] = f(n)
        return cache[n]
    return memoized
>>> counted_fib = count(fib)
>>> fib  = memo(counted_fib)
>>> fib(19)
4181
>>> counted_fib.call_count
20
>>> fib(34)
5702887
>>> counted_fib.call_count
35

我们发现 call_count 的数目相比 recursive fib 明显变小了

更高级的 python 写法就是 decorator

def debug(func): # decorator: 接受一个函数作为参数,并返回另一个函数
    def wrap(*args, **kwargs):
        func(*args, **kwargs)
        print("[DEBUG] '%s' model called." % (func.__name__))
    return wrap

@debug
def testfunc():
    print("Hello World")

testfunc()

...>
Hello World
[DEBUG] 'testfunc' model called.
...>

9.7
Charlie
海宁 CS61A_self_study

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值