我试图计算一个类中的函数obtainingparams
被调用的次数,并且正在使用下面给出的装饰器counted
来完成此操作。我知道这可以在类之外进行,但是,我在行TypeError: counted() missing 1 required positional argument: 'fn'
中收到错误@counted
,并且不知道如何处理。
def counted(self, fn):
def wrapper(*args, **kwargs):
wrapper.called+= 1
return fn(*args, **kwargs)
wrapper.called= 0
wrapper.__name__= fn.__name__
return wrapper
@counted
def obtainingparams(self, df, tau_1, tau_2, residuals):
print('Does something')
谢谢
最佳答案
假设未在类内定义计数,请执行以下操作:
def counted(fn):
def wrapper(*args, **kwargs):
wrapper.called+= 1
return fn(*args, **kwargs)
wrapper.called= 0
wrapper.__name__= fn.__name__
return wrapper
class MyClass(object):
@counted
def obtainingparams(self, df, tau_1, tau_2, residuals):
print('Does something')
您将自己置入装饰器的唯一原因是,如果您正在执行以下操作:
class MyDecorator(object):
def __init__(self):
self.called = 0
def counted(self, fn):
def wrapper(*args, **kwargs):
self.called += 1
return fn(*args, **kwargs)
wrapper.__name__= fn.__name__
return wrapper
a_dec = MyDecorator()
class MyClass(object):
@a_dec.counted
def obtainingparams(self, df, tau_1, tau_2, residuals):
print('Does something')
关于python - 计算在类中调用一个函数的次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31619565/