摘要:
# 把装饰器定义为类
# 定义中需要实现__call__(),__get__() 方法
import types
from functools import wraps
class Profiled:
def __init__(self, func):
wraps(func)(self)
self.ncalls = 0
def __call__(self, *args, **kwargs):
self.ncalls += 1
return self.__wrapped__(*args, **kwargs)
def __get__(self, instance, cls):
if instance is None:
return self
else:
return types.MethodType(self, instance)
# 在类外使用装饰器
@Profiled
def add(x, y):
re
阅读全文