计算在类

时间:2015-07-24 20:51:23

标签: python

我正在尝试计算类中函数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')

谢谢

1 个答案:

答案 0 :(得分:3)

假设count未在类中定义,请执行以下操作:

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')