• In Python, a decorator turns a function into another function.

  • A decorator can be either a class or a function.

  • A decorator with arguments has a different syntax than one without arguments.



Python decorators.

# Example function.
def foo(n):

# Function decorator 1.
def fdec1(func):
    def bar(n):
        print('fdec1: {}'.format(n + 1))
    return bar

# Function decorator 2.
def fdec2(arg):
    def fdec2x(func):
        def bar(n):
            print('fdec2: {}'.format(n + arg))
        return bar
    return fdec2x

# Class decorator 1.
class cdec1:
    def __init__(self, func):
        print('cdec1: init')

    def __call__(self, n):
        print('cdec1: {}'.format(n + 1))

# Class decorator 2.
class cdec2:
    def __init__(self, arg):
        self.arg = arg
        print('cdec2: init')

    def __call__(self, func):
        def bar(n):
            print('cdec2: {}'.format(n + self.arg))
        return bar

# Uncomment any of these decorators.

def foo(n):
    print('foo: {}'.format(n))