decorator over method python code example

Example 1: python function decorator

#Decorator are just function that take function as first
#parameter and return a function
def logging(f):
  def decorator_function(*args, **kwargs):
    print('executing '+f.__name__)
    return f(*args, **kwargs)
  return decorator_function
#Use it like this
@logging
def hello_world():
  print('Hello World')
#calling hello_world() prints out:
#executing hello_world
#Hello World

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!')