[英]Python decorator class with function counter variable
我在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)
我想这取决于您要如何计算。 例如:
>>> class A(object):
>>> pass
>>> ...
>>> def foo(obj):
>>> def inner(*args, **kwargs):
>>> counter += 1
>>> print "times called: %d" % counter
>>> counter = 0
>>> return inner
>>> Bar = A()
>>> Bar.eggs = foo(Bar)
>>> Bar.foo()
times called: 1
>>> Bar.foo()
times called: 2
>>> Spam = A()
>>> Spam.eggs = foo(Spam)
>>> Spam.eggs()
times called: 1
之所以an_object.foo
,是因为包装器将随身携带其环境,这意味着在包装时, counter
在an_object.foo
的任何给定实例的范围内。 尽管它可能不像您需要的那样内省。 或者,您是说要计算obj.foo
实际被调用的总次数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.