首页 > 编程语言 > 详细

python函数与方法装饰器

时间:2015-12-29 22:34:19      阅读:240      评论:0      收藏:0      [点我收藏+]

之前用python简单写了一下斐波那契数列的递归实现(如下),发现运行速度很慢。

def fib_direct(n):
    assert n > 0, ‘invalid n‘
    if n < 3:
        return n
    else:
        return fib_direct(n - 1) + fib_direct(n - 2)

然后大致分析了一下fib_direct(5)的递归调用过程,如下图:

技术分享

住:这里的f(2)调用f(1)仅代表基本操作的次数。

可以看到多次重复调用,因此效率十分低。进一步,可以算出递归算法的时间复杂度。T(n) = T(n-1) + T(n-2),用常系数线性齐次递推方程的解法,解出递推方程的特征根,特征根里最大的n次方就是它的时间复杂度O(1.618^n),指数级增长。

为了避免重复调用,可以适当地做缓存,python的装饰器可以完美的完成这一任务。

装饰器:基础


python中一切都是对象,这里需要强调函数是对象为了更好地理解函数也是对象,下面结合代码片段来说明这一点。

#! /usr/bin/env python
def shout(word=‘yes‘):
	return word.capitalize() + ‘!‘
print shout()

#outputs:Yes!

‘‘‘
As an object, you can assign the function to a variable like any other object.
Notece we don‘t use parentheses: we are not calling the function,
we are putting the function ‘shout‘ into the variable ‘scream‘.
‘‘‘
scream = shout
print scream()

#outputs:Yes!

‘‘‘
More than that, it meams you can remove the old name ‘shout‘,
and the function will still be accessible from ‘scream‘.
‘‘‘
del shout
try:
	print shout()
except NameError, e:
	print e
#outputs:name ‘shout‘ is not defined

print scream()
#outputs:Yes!

http://selfboot.cn/2014/08/10/python_decorator/

python函数与方法装饰器

原文:http://www.cnblogs.com/stemon/p/5087062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!