1、使用‘@’来使用decorator
2、注意装饰器的使用顺序
3、"@deco" ,“deco(myfunc())” 只是效果一致,但类型不同
4、如果直接deco(myfunc())调用,方法名带()作为参数,但是在创建decorator时,参数为方法名,不带()
5、装饰器中是两层方法调用,应该是为了避免死循环,可以尝试一层调用就知道了
创建一个装饰器
import time
# 思考下为什么装饰器中是两层方法调用呢?
def deco(func):
def wrapper():
starttime = time.time()
func()
endtime = time.time()
msecs = (endtime - starttime)*1000
print (">elapsed time: %f ms" % msecs)
return wrapper
# def wrapper(func):
# print('+++')
# func()
# print('---')
# return wrapper
# 返回自己导致无限调用自己
#调用装饰器
@deco
def myfunc():
print 'starttime'
time.sleep(0.6)
print 'endtime'
print "myfunc is ",myfunc.__name__
myfunc()
deco(myfunc()) # 虽然效果一致,但是type并不相同,参考下面代码
多层装饰器的装饰规则
#个人称其为:就近原则
@second
@first
def myfunc():
pass
myfunc()
second(first(myfunc())) # 虽然效果一致,但是type并不相同,参考下面代码
它们type并不相同
执行:
a = myfunc()
print(type(a))
b = deco(myfunc())
print(type(b))
print(a==b)
结果:
<class 'NoneType'>
<class 'function'>
False