python中的修饰器@…
浅谈python修饰器
- 修饰器就是为已经存在的对象,添加一些其他的功能
较为经典的有插入日志,性能检测,如运行该函数所耗费的时间,事件处理等 - 利用修饰器方便代码重用
- 被修饰函数做为修饰函数的参数!!!
exampleOne
def make_bold(fn):
def wrapped():
return "<b>"+fn()+"<b>"
return wrapped
def make_i(fn):
def wrapped():
return "<i>"+fn()+"<i>"
return wrapped
'''注意这两个修饰(包装)器的使用顺序'''
@make_bold # 相当于是make_bold(hello())
@make_i # 相当于是make_i(hello())
def hello():
return "hello"
print(hello())
# result: <b><i>hello<i><b>
exampleTwo:统计函数运行所耗时间
import time
def time_it(func):
def wrapper():
start=time.clock()
func()
end=time.clock()
print( 'the cost time of this function is', end-start)
return wrapper
@time_it
def f1():
print("this is a function")
# result:this is a function ,the cost time of this function is 1.6e-05