统计函数被调用次数的装饰器
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