Search code examples
pythondecoratorwrapperclass-method

how to use decorator in class method


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


Solution

  • @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()