Код: Выделить всё
class myclass:
def __init__(self):
self.cnt = 0
def counter(function):
"""
this method counts the 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 method counts the 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)
РЕДАКТИРОВАТЬ: ------
Во-первых, я не могу определить украшение вне метода класса. Во-вторых, я пытаюсь создать запланированный класс, который запускает определенную функцию (в качестве входных данных) в течение фиксированного интервала и определенного количества времени, поэтому мне нужно ее посчитать.
Подробнее здесь: https://stackoverflow.com/questions/499 ... side-class
Мобильная версия