A function that takes one function as input and returns another. Use when you want to do something before or after a function.
Example
#Decorator
def test(func):
def new_func(*args, **kwargs):
print("start")
result = func(*args, **kwargs)
print("end")
return result
return new_func
#Decorator target
#Decorated by annotating
@test
def greeting():
print("Hello")
greeting()
result
start
Hello
end
Example
#About decorators
#dump is called and func=Run as double
def dump(func):
"Display input arguments and output values"
def wrapped(*args, **kwards):
print("Fuction name: %s" % func.__name__)
print("Input arguments: %s " % ' '.join(map(str, args)))
print("Input keyaeorods: %s " % kwards.items())
output = func(*args, **kwards)
print("Output:", output)
return wrapped
@dump
def double(*args, **kwards):
"Double every arguments"
output_list = [2 * args for arg in args]
output_dict = {k: 2 * v for k, v in kwards.items()}
return output_list, output_dict
result
Fuction name: double
Input arguments: 3 5
Input keyaeorods: dict_items([('first', 100), ('next', 98.6), ('last', 40)])
Output: ([(3, 5, 3, 5), (3, 5, 3, 5)], {'first': 200, 'next': 197.2, 'last': 80})
"Introduction to Python 3" (Author: Bill Lubanovic)
Recommended Posts