python装饰器实例
函数装饰器:
#!/usr/bin/python # --*-- coding:utf-8 --*-- # 类型一:装饰器无参数;调用函数无参数 def decorator01(func): print "this is calling decorator01!" def wrapper(): func() return wrapper @decorator01 def func01(): print "this is calling func01!" # 执行 func01() print '---------------------' # 类型二:装饰器无参数;调用函数有参数,参数通用化 def decorator02(func): print "this is calling decorator02!" def wrapper(*args, **kwargs): func(*args, **kwargs) return wrapper @decorator02 def func02(name): print "this is calling func02!, name is %s" % (name) # 执行 func02('wsongl-2') print '---------------------' # 类型三:装饰器无参数;调用函数有参数,参数具体化 def decorator03(func): print "this is calling decorator03!" def wrapper(name): func(name) return wrapper @decorator03 def func03(name): print "this is calling func03!, name is %s" % (name) # 执行 func03('wsongl-3') print '---------------------' # 类型四:装饰器有参数;调用函数无参数 def decorator04(dec): def wrapper(func): print 'thi is decorator argms: %s' % (dec) def inner(): func() return inner return wrapper @decorator04('log-4') def func04(): print "this is calling func04!" # 执行 func04() print '---------------------' # 类型五:装饰器有参数;调用函数有参数,参数通用化,具体参数同上则可 def decorator05(dec): def wrapper(func): print 'thi is decorator argms: %s' % (dec) def inner(*args, **kwargs): func(*args, **kwargs) return inner return wrapper @decorator05('log-5') def func05(name): print "this is calling func05!, name is %s" % (name) # 执行 func05('wsongl-5') print '---------------------' 执行结果如下: this is calling decorator01! this is calling func01! --------------------- this is calling decorator02! this is calling func02!, name is wsongl-2 --------------------- this is calling decorator03! this is calling func03!, name is wsongl-3 --------------------- thi is decorator argms: log-4 this is calling func04! --------------------- thi is decorator argms: log-5 this is calling func05!, name is wsongl-5 ---------------------
类装饰器:
#!/usr/bin/python # --*-- coding:utf-8 --*-- # 装饰类无参数 class Decorator01(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): print 'this is calling func __call01__' return self.func(*args, **kwargs) @Decorator01 def wsongl06(): print 'this is calling wsongl06' wsongl06() print '---------------------' # 装饰类有参数 class Decorator02(object): def __init__(self, info='error'): self.info = info def __call__(self, func): def wrapper(*args, **kwargs): print 'this is calling func __call02__, info is %s' % ( self.info ) return func(*args, **kwargs) return wrapper @Decorator02(info='debug') def wsongl07(): print 'this is calling wsongl07' wsongl07() print '---------------------' 执行结果如下: this is calling func __call01__ this is calling wsongl06 --------------------- this is calling func __call02__, info is debug this is calling wsongl07 ---------------------