【发布时间】:2018-10-03 01:40:08
【问题描述】:
我正在尝试在我的类中创建一个方法来计算特定函数的完整运行。我想使用一个简单的装饰器。我找到了这个reference 并重写了这个简单的脚本:
class myclass:
def __init__(self):
self.cnt = 0
def counter(function):
"""
this method counts the number of runtime of a function
"""
def wrapper(self, **args):
function(**args)
self.counter += 1
return wrapper
@myclass.counter
def somefunc():
print("hello from somefunc")
if __name__ == "__main__":
obj = myclass()
# or if comment @myclass.counter
# somefunc = myclass.counter(somefunc)
somefunc()
当然我得到:
TypeError: wrapper() missing 1 required positional argument: 'self'
我尝试将计数器重写为类方法:
class myclass:
def __init__(self):
self.cnt = 0
def counter(self, function):
"""
this function counts the number of runtime of a function
"""
def wrapper(**args):
function(**args)
self.cnt += 1
return wrapper
def somefunc():
print("hello from somefunc")
if __name__ == "__main__":
obj = myclass()
somefunc = obj.counter(somefunc)
for i in range(10):
somefunc()
print(obj.cnt)
这很好,但我认为它不是一个有效的装饰器定义。有没有办法在类方法中定义装饰器并将自参数传递给它的函数?还是在类中定义装饰器没用?
编辑:------ 首先,我无法在类方法之外定义装饰。其次,我正在尝试创建一个计划类,该类在固定间隔和特定时间量内运行特定函数(作为输入),因此我需要对其进行计数。
【问题讨论】:
-
Python decorators count function call 的可能重复项您也可以查看
self和__init__here 是什么 -
@iam.Carrot 谢谢,但我的装饰器定义必须在我的类(方法或其他)中,因为它必须计入我的日程安排。
-
it must count for my schedule到底是什么意思? -
@iam.Carrot 我正在创建一个计划类,它运行特定函数作为特定时间的输入。我需要计算内部函数的运行时间,然后终止调度。
-
您是要维护所有实例的计数还是要处理单个实例的计数。例如,如果我创建 10 个实例,并从每个实例调用该方法 5 次,您希望计数为 50 还是仅 5?