How are decorators implemented with a class in Python?

Viewed 58
def decorator_function(original_function):
    def wrapper_function():
        print('wrapper_function executed before {}'.format(original_function.__name__))
        return original_function()
    return wrapper_function

@decorator_function   
def display():
    print('display function ran...')

The above syntax can be translated as follows: display = decorator_function(display)

The same thing can be done with a class...

class decorator_class(object):

    def __init__(self, original_function):
        self.original_function = original_function

    def __call__(self):
        print('call method before {}'.format(self.original_function.__name__))
        self.original_function()

@decorator_class
def display():
    print('display function ran...')

I can understand this implementation. But I don't understand how the syntax gets translated behind the hood, like I mentioned in case of a decorator_function. I am also unable to comprehend how decorators are implemented with @classmethod and @staticmethod. Can someone please help out with an example?

0 Answers
Related