简体   繁体   English

计算在类中调用一个函数的次数

[英]Counting number of times a function is called within a Class

I am trying to count the number of times the function obtainingparams within a class has been called and am using the decorator counted given below to do this. 我想算的次数函数的数量obtainingparams类中已经调用了现在用的装饰counted如下做到这一点。 I know that this would work outside of a class, however, I get the error TypeError: counted() missing 1 required positional argument: 'fn' in the line @counted and don't know how to deal with this. 我知道这将在类之外起作用,但是,我收到错误TypeError: counted() missing 1 required positional argument: 'fn'@counted行中TypeError: counted() missing 1 required positional argument: 'fn' ,并且不知道如何处理。

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

Thank You 谢谢

Assuming counted is not defined inside a class then do the following: 假设未在类内定义计数,请执行以下操作:

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

The only reason you would put self on a decorator would be if you were doing something like this: 您将自己置入装饰器的唯一原因是,如果您正在执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM