我在 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)
然后如何从我的装饰器类中获取计数器值?
请您参考如下方法:
您向我们展示的类不是装饰器——它只是一个类。访问柜台就这么简单
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)
