Python Decorators
-
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.
Example
#!/usr/bin/python
'''
Python decorators.
'''
# Example function.
def foo(n):
print(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.
#@fdec2(10)
#@fdec1
#@cdec2(10)
#@cdec1
def foo(n):
print('foo: {}'.format(n))
foo(88)
foo(88)