这个装饰器很像Java的注解....
一级装饰器(不带参数)
#!/usr/bin/env python # -*- coding: utf-8 -*- # time @2016/3/11 15:13 create by JasonYang def decorate(func): def wrapper(*args, **kwargs): print "call function named %s" % func.__name__ func(*args, **kwargs) return wrapper @decorate def test(): print 'bob' test()
运行结果:
call function named test bob
二级装饰器(带参数)
def decorate_2(param): def decorate_(func): def wrapper_(*args, **kwargs): print 'hello i am decorator 2', str(param) print "call function named %s" % func.__name__ func(*args, **kwargs) return wrapper_ return decorate_ @decorate_2('装饰器') def f(): print 'alice' f()
运行结果:
hello i am decorator 2 装饰器 call function named f alice