Mstfa Uyar
Mstfa Uyar

Reputation: 5

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

Upvotes: 0

Views: 370

Answers (1)

Feras Alfrih
Feras Alfrih

Reputation: 520

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

Upvotes: 1

Related Questions