最简易的包装:
def myfunc():
pass
def deco(f):
print('before')
f()
print('after')
return f #若python有能力在此返回deco本身 则 deco即可作为装饰!
test.py
class mylocker:
def __init__(self):
print("mylocker.__init__() called.")
@staticmethod
def acquire():
print("mylocker.acquire() called.")
@staticmethod
def unlock():
print(" mylocker.unlock() called.")
class lockerex(mylocker):
@staticmethod
def acquire():
print("lockerex.acquire() called.")
@staticmethod
def unlock():
print(" lockerex.unlock() called.")
def lockhelper(cls):
'''cls 必须实现acquire和release静态方法'''
def _deco(func):
def __deco(*args, **kwargs):
print("before %s called." % func.__name__)
cls.acquire()
try:
return func(*args, **kwargs)
finally:
cls.unlock()
return __deco
return _deco
test2.py
from test import *
class example:
@lockhelper(mylocker)
def myfunc(self):
print(" myfunc() called.")
@lockhelper(mylocker)
@lockhelper(lockerex)
def myfunc2(self, a, b):
print(" myfunc2() called.")
return a + b
if __name__=="__main__":
a = example()
# a.myfunc()
# print(a.myfunc())
# print(a.myfunc2(1, 2))
print(a.myfunc2(3, 4))
result:
before __deco called.
mylocker.acquire() called.
before myfunc2 called.
lockerex.acquire() called.
myfunc2() called.
lockerex.unlock() called.
mylocker.unlock() called.
7