python中的装饰函数
在面向对象(OOP)的设计模式中,decorator被称为装饰模式。OOP的装饰模式需要通过继承和组合来实现,而Python除了能支持OOP的decorator外,直接从语法层次支持decorator。Python的decorator可以用函数实现,也可以用类实现。
decorator可以增强函数的功能,定义起来虽然有点复杂,但使用起来非常灵活和方便。
请编写一个decorator,能在函数调用的前后打印出'begin call'
和'end call'
的日志。
再思考一下能否写出一个@log
的decorator,使它既支持:
@log
def f():
pass
又支持:
@log('execute')
def f():
pass
1 #heelo.py 2 __author__ = 'Administrator' 3 import functools 4 def log(text=None): 5 def de(func): 6 @functools.wraps(func) 7 def first(*args,**kw): 8 if text : 9 print "begin call",func.__name__,'input is ',text 10 else: 11 print "begin call",func.__name__ 12 rs= func(*args,**kw) 13 print 'end call' 14 return rs 15 return first 16 17 return de 18 19 @log() 20 def now(): 21 print 'I\'m a boy ' 22 23 24 now() 25 print now.__name__
数学原形
-------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------
1 #!/usr/bin/env python 2 from time import ctime,sleep 3 def tsfunc(func): 4 def wrappedFunc(*args,**kwargs): 5 print '[%s] %s () called ' % (ctime(), func.__name__) 6 return func 7 return wrappedFunc 8 9 10 @tsfunc 11 def foo(): 12 pass 13 14 foo() 15 sleep(4) 16 for i in range(2): 17 sleep(1) 18 foo()
输出:
[Tue Jul 14 20:49:18 2015] foo () called
[Tue Jul 14 20:49:23 2015] foo () called
[Tue Jul 14 20:49:24 2015] foo () called