0

how to use decorator in class method

import time


def myTimer(func, *args, **kwargs):
    def wrapper():
        start = time.perf_counter()
        func(*args, **kwargs)
        elapsed_time = time.perf_counter() - start
        print(elapsed_time)

    return wrapper


class Example:
    def __init__(self):
        pass

    @myTimer
    def data(self):
        return [i for i in range(10000)]


e = Example()
e.data()

out_put = TypeError: wrapper() takes 0 positional arguments but 1 was given

1
  • 1
    The *args, **kwargs parameters should be on wrapper, not myTimer. Commented Jan 2, 2022 at 12:54

1 Answer 1

1

@khelwood said that first, but i was trying this edit

def myTimer(func):
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        func(*args, **kwargs)
        elapsed_time = time.perf_counter() - start
        print(elapsed_time)

    return wrapper


class Example:
    def __init__(self):
        pass

    @myTimer
    def data(self):
        return [i for i in range(10000)]


e = Example()
e.data()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.