gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:05:19 26 4
gpt4 key购买 nike

我在 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)

关于具有函数计数器变量的 Python 装饰器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22490705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com