#!/usr/bin/python**加粗文字**
def deco_functionNeedDoc(func):
if func.__doc__ == None:
print func,"has no __doc__, it's a bad habit."
else:
print func,':',func.__doc__,'.'
return func
@deco_functionNeedDoc
def f():
print 'f() Do something'
@deco_functionNeedDoc
def g():
'I have a __doc__'
print 'g() Do something'
f()
g()
Actual Result:
<function f at 0x7f31e65d05f0> has no __doc__, it's a bad habit.
<function g at 0x7f31e65d0668> : I have a doc .
f() Do something
g() Do something
Expected Result:
<function f at 0x7f31e65d05f0> has no __doc__, it's a bad habit.
f() Do something
<function g at 0x7f31e65d0668> : I have a doc .
g() Do something
f()和g()被修饰后是如何执行的?
另外一段使用装饰器的代码
#-*- coding: UTF-8 -*-
import time
def timeit(func):
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return wrapper
@timeit
def foo():
print 'in foo()'
foo()
Actual Result:
in foo()
used: 2.1e-05
这一段使用wrapper方法执行时先执行foo(),再执行wrapper()。
加了wrapper会有什么差别吗?
装饰器更像是“编译时”所执行的程序,即使在原函数还未装载入内存前就先为函数进行“装饰”工作,所以这里是先进行装饰,再运行的装饰后的函数。不然,你试试在最后不执行f()、g()同样可以执行装饰函数里面的代码