带有函数计数器变量的Python装饰器类

时间:2014-03-18 20:48:29

标签: python class object decorator

我有Python类,我需要将其用作装饰器类,但我想在调用时计算一些东西:

class SomeClass:

    counter = 0

    @staticmethod
    def some_function(a):
        """
        -----------------------
        Does something
        -----------------------
        """
        SomeClass.counter += 1
        a = a * a
        return a

致电后:

a = new_var.some_function(a) 

然后如何从装饰器类中获取计数器值?

1 个答案:

答案 0 :(得分:1)

你向我们展示的课程不是一个装饰者 - 它只是一个类。访问计数器就像

一样简单
SomeClass.counter
# current counter value

让您的课程成为一名真正的装饰师并不困难 - 但我会将其重命名为Counter

class Counter:
    """
    Count the number of calls made to the wrapped function.
    """
    def __init__(self, func):
        self.counter = 0
        self.func = func
    def __call__(self, *args, **kwds):
        self.counter += 1
        return self.func(*args, **kwds)

@Counter
def square(n):
    return n * n

并在使用中:

square(3)
# 9
square(7)
# 41
square(11)
# 121

square.counter
# 3

注意:这是一个非常简单的装饰器,一个副作用是包装函数的签名丢失。

未打开的签名:

Help on function square in module __main__:
square(n)

包装签名:

Help on instance of Counter in module __main__:
class Counter
 |  Count the number of calls made to the wrapped function.
 |  
 |  Methods defined here:
 |  
 |  __call__(self, *args, **kwds)
 |  
 |  __init__(self, func)