装饰器:不改变原函数的基础上,给函数增加功能的方式,称为装饰器
即:为已经存在的对象添加额外的功能
装饰器其实就是一个闭包,把一个函数当做参数后返回一个替代版的函数
decos.py:
(装饰器的参数类)代码如下:
class Locker1: def __init__(self): print('locker1...') @staticmethod def acquire(): print('locker1 acquire...') @staticmethod def unlock(): print('locker1 unlock...')
class Locker2(Locker1): @staticmethod def acquire(): print('locker2 acquire...') @staticmethod def unlock(): print('locker2 unlock...')
装饰器函数 和 主程序:
# 装饰器函数: def locker_deco(cls): def _deco(func): def __deco(*args,**kwargs): print('before...') print(func.__name__) cls.acquire() try: return func(*args,**kwargs) finally: cls.unlock() print('after...') return __deco return _deco # 主程序: from decos import Locker1,Locker2 class Example: @locker_deco(Locker1) def func1(self): print('func1...') return 5 @locker_deco(Locker1) @locker_deco(Locker2) def func2(self,a,b): print('func2...') return a+b e=Example() e.func2(1,2) print('****') print(e.func2(1,2))
运行结果:
before... __deco locker1 acquire... before... func2 locker2 acquire... func2... locker2 unlock... locker1 unlock... **** before... __deco locker1 acquire... before... func2 locker2 acquire... func2... locker2 unlock... locker1 unlock... 3