Press "Enter" to skip to content

Applying Decorators to Class in Python

The following is an example of a Python program for applying Decorators to Class.

Applying Decorators to Class in Python Example

Applying Decorators to Class in Python is very easy, but you should use decorators before @classmethod. Below example also illustrates to applying Decorators to the Static methods:

import time
from functools import wraps

# A simple decorator
def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        r = func(*args, **kwargs)
        end = time.time()
        print(end-start)
        return r
    return wrapper

# Class illustrating application of the decorator to different kinds of methods
class Spam:
    @timethis
    def instance_method(self, n):
        print(self, n)
        while n > 0:
            n -= 1

    @classmethod
    @timethis
    def class_method(cls, n):
        print(cls, n)
        while n > 0:
            n -= 1

    @staticmethod
    @timethis
    def static_method(n):
        print(n)
        while n > 0:
            n -= 1

if __name__ == '__main__':
    s = Spam()
    s.instance_method(10000000)
    Spam.class_method(10000000)
    Spam.static_method(10000000)

Output

<__main__.Spam object at 0x100c8e9e8> 10000000
0.5970339775085449
<class '__main__.Spam'> 10000000
0.588432788848877
10000000
0.5878908634185791

Related Tutorials:

Vinish Kapoor

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

Comments are closed.