创建一个类装饰器,该装饰器本身就是一个类

时间:2021-03-17 13:01:31

标签: python-3.x python-decorators python-class

我需要一个带有静态变量的装饰器,它基本上是一个计数器。所以它需要是一个类,因为我们在python中似乎没有静态变量。 从代码中可能很清楚我要做什么。

class decorator_class:
    counter = 0
    def __init__(self,cls,*args,**kwargs):
        self.cls,self.args,self.kwargs=cls,args,kwargs
    def __call__(self):
        t1 = time.time()
        instance=self.cls()
        t2 = time.time()
        print('It took: {}'.format(t2 - t1))
        self.counter=self.counter+(t2-t1)
        print('Total time: {}'.format(self.counter))

        return(instance)

class Target:
    def __init__():
        print("Target running")

decorator_class(Target)()

以上方法无效。

还要求类 Target 在其 __init__ 构造函数中可以有参数。

0 个答案:

没有答案
相关问题