這個裝飾器很像Java的註解....python
一級裝飾器(不帶參數)bash
#!/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()
運行結果:app
call function named test bob
二級裝飾器(帶參數)spa
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()
運行結果:code
hello i am decorator 2 裝飾器 call function named f alice
將裝飾器定義爲類:utf-8
# -*- coding:utf-8 -*- # 2016/10/21 # mail:ybs.kakashi@gmail.com """ 類裝飾器 """ class DecoratorClass: def __init__(self, func): self.func = func self.ncalls = 0 def __call__(self, *args, **kwargs): self.ncalls += 1 return self.func(*args, **kwargs) @DecoratorClass def add(a, b): return a + b print "--", add.ncalls print add(1, 2) print "--", add.ncalls print add(1, 3) print "--", add.ncalls
結果:it
D:\Python27\python.exe E:/workspace/xx/decorator/test1.py -- 0 3 -- 1 4 -- 2 Process finished with exit code 0