惯例,从一段代码出发:
def timeCompute(fn):
def wrapFn(*args):
start = datetime.datetime.now()
result = fn(*args)
end = datetime.datetime.now()
print 'use time in %s' % fn.__name__, end - start
return result
return wrapFn
@timeCompute
def doNothing():
print 'i do nothing but sleep 3s'
print 'now i begin to sleep...'
time.sleep(3)
print 'now i\'m awake'
doNothing()
doNothing方法什么都没做,就是sleep了3秒,我想看下这个3秒它是不是真的sleep了,所以我实现了一个timeCompute,通过at符号,调用装饰器的方式来进行了调用,调用后发现结果打印如下:
i do nothing but sleep 3s
now i begin to sleep...
now i'm awake
use time in doNothing 0:00:02.999587
好吧,结果和预想的差不多。
这里就是介绍了一个简单的装饰器的用法。python里都是对象,doNothing函数也是一个对象,可以用来进行当参数进行传参,那么真正执行的时候就是执行timeCompute(doNothing)
基本思路就是这样了,通过装饰器,你可以把一些通用的部分给提取出来,从而实现代码简化。
看了上面这段代码,估计你还是没法了解装饰器在实际中有啥用,这里再给一个装饰器的比较经典的例子。
iProcNum = 0
def fib(i):
global iProcNum
iProcNum += 1
if i > 2:
return (fib(i - 1) + fib(i - 2))
else:
return i
这个是一个计算斐波那契数列的函数,很简单,通过递归实现。调用10次的代码如下:
for i in range(10):
print "fib %d is %d" % (i, fib(i))
print "total proc num:", iProcNum
增加了一个iProcNum参数用来表示这个函数在调用了10次后一共执行的次数,结果如下:168次
fib 0 is 0
fib 1 is 1
fib 2 is 2
fib 3 is 3
fib 4 is 5
fib 5 is 8
fib 6 is 13
fib 7 is 21
fib 8 is 34
fib 9 is 55
total proc num: 168
通过装饰器我们可以把这段代码给简化,如下:
def memo(fn):
cache = {}
def wrapNewFib(*args):
if args[0] not in cache.keys():
cache[args[0]] = fn(args[0])
return cache[args[0]]
return wrapNewFib
@memo
def newFib(i):
global iProcNum
iProcNum += 1
if i > 2:
return (newFib(i - 1) + newFib(i - 2))
else:
return i
通过cache,把结果给保留下来,等到需要的时候直接读cache,就把递归的变成了线性复杂度,再调用10次,结果如下:
fib 0 is 0
fib 1 is 1
fib 2 is 2
fib 3 is 3
fib 4 is 5
fib 5 is 8
fib 6 is 13
fib 7 is 21
fib 8 is 34
fib 9 is 55
total proc num in newFib: 10
只需要调用10次就可以了
当调用次数变到30次后,执行时间的变化如下:
直接递归:
total proc num: 2692508
use time: 0:00:00.872364
装饰器cache:
total proc num in newFib: 30
use time: 0:00:00.000352
优化效果还是很明显的。
装饰器也可以带参数,我这里和对于类的装饰器一起给出例子:
class classDeco:
def __init__(self, fn):
print "in classDeco init"
self.fn = fn
def __call__(self):
print 'in classDeco call'
self.fn()
@classDeco
def classDecoDemo():
print 'i \'ll be called'
classDecoDemo()
class classDecoArg:
def __init__(self, a):
print "in classDecoArg init"
print "i've got an arg:", a
def __call__(self, fn):
def wrapper():
print 'in classDecoArg call'
fn()
return wrapper
@classDecoArg(5)
def classDecoArgDemo():
print "i'll be called by classDecoArg"
classDecoArgDemo()
这里需要注意的有以下几点:
1.关于类的装饰器,需要实现__call__方法;
2.如果装饰器不带参数,函数对象需要传递到__init__方法中,如果装饰器带参数,那么是传递到__call__方法
3.关于参数的传递可以自己看下*args和**kwargs
4.最终函数的调用都是__call__方法
python自带的装饰器中比较常用的有这3个:staticmethod、classmethod、property
还是通过一个例子来说明:
class pythonDeco:
a = 1
def __init__(self):
print 'in pythonDeco init'
self.b = 2
def funcInClass(self):
print 'i can invoke b:%d' % self.b
@staticmethod
def staticmethodDemo():
print 'you can invoke static method with class name'
@classmethod
def classmethodDemo(cls):
print 'i can invoke a:%d' % cls.a
@property
def propertyDemo(self):
return self.c
@propertyDemo.setter
def propertyDemo(self, value):
self.c = value
@propertyDemo.deleter
def propertyDemo(self):
del self.c
pythonDeco.staticmethodDemo()
ob = pythonDeco()
ob.funcInClass()
ob.classmethodDemo()
ob.c = 3
print ob.c
del ob.c
分别表示类的静态方法,类方法,和属性定义,这段代码应该写的比较详细了。。。有问题再说吧