python中的装饰器有一点点像是java中的AOP,就是在执行你的一个方法前可以做一些通用的工作,当然了,用多重继承也可以实现减少代码量的功能,但是使用装饰器更加“非侵入”。
# -*- coding:utf-8 -*- #!/usr/bin/python def preProcessWithoutParams(f1): '''无参数装饰器''' def func(): print "使用装饰器(无参数)初始化过程" return f1 return func() def preProcessWithParams(f1): '''带参数的装饰器''' def func(name): print "使用装饰器(有参数)初始化过程" return f1(name) return func @preProcessWithoutParams def func1(): print "execute function1" @preProcessWithParams def func2(name): print "execute function2 " + name func1() print("") func2("jim")
执行后的输出如下
使用装饰器(无参数)初始化过程 execute function1 使用装饰器(有参数)初始化过程 execute function2 jim
