decorator in class python code example

Example 1: decorator python

def our_decorator(func):
    def function_wrapper(x):
        print("Before calling " + func.__name__)
        func(x)
        print("After calling " + func.__name__)
    return function_wrapper

@our_decorator
def foo(x):
    print("Hi, foo has been called with " + str(x))

foo("Hi")

Example 2: python decorator in class with self

class Dog:
    def __init__(self, name):
        self.name = name
        
    def say_name(func):
        def decorator(*args, **kwargs):
            # self is always the first argument
            self = args[0]
            print(self.name)
            return func(*args, **kwargs)
        return decorator
    
    @say_name
    def bark(self):
        print('woof!')