統計函數被調用次數的裝飾器
import functools
def counter(func):
@functools.wraps(func)
def tmp(*args, **kwargs):
tmp.count += 1
return func(*args, **kwargs)
tmp.count = 0
return tmp
@counter
def func():
print(func.count)
func() #1
func() #2
func() #3
類中的某個方法用于裝飾類中的其他方法
from operator import methodcaller
def do_something(funName='other', a='hello', b='world'):
def wrapper(fun):
def inner(*args, **kwargs):
cls = args[0]
methodcaller(funName,a=a,b=b)(cls)
print(f'調用了方法{funName},參數a={a},參數b={b}')
return fun(*args, **kwargs)
return inner
return wrapper
class Clazz():
@do_something()
def func(self, x, y):
c = x + y
print('{}+{}={}'.format(x, y, c))
@do_something(funName='other',a='你好',b='世界')
def func2(self, x, y):
c = x + y
print('{}+{}={}'.format(x, y, c))
def other(self, a, b):
print(f'a is {a},b is {b}')
if __name__ == '__main__':
c =Clazz()
c.func(x=1,y=2)
# a is hello,b is world
# 調用了方法done,參數a=hello,參數b=world
# 1+2=3
c.func2(x=100,y=200)
# a is 你好,b is 世界
# 調用了方法other,參數a=你好,參數b=世界
# 100+200=300