This example shows a simple use of the decorators with python to add functionality to a function of a method without changing them. If you need to understande them well, take a look at these posts:
- decorators 1
- decorators 2
- decorators 3 (this one)
- decorators 4
Python decorator example
In this example you add some way to display some infos about a function, with a decorator, an external function that uses some data from the original function to add some features to it. The two functions that uses the same decorator (so you can save some code and make it more usable and re-usable) are made to just return a sum or a subtraction of two numbers. The decorator ‘decorate’ the result printing the result in a more verbose way, explaining what the functions do.
In this type of decorator, differently from the example we’ve see in the previous posts, we can pass an argument to the decorator, throught the ‘pie’ symbol @dec… to call the decorator. In this way you can pass the ‘+’ or ‘-‘ symbol to differentiate the output that fits the function that uses the same decorator.
def dec(operator=""): def features(fn): def add_some_decorations(a, b): res = fn(a, b) print("\n") print(f"Function: {fn.__name__}({a}, {b})") print("Operator: ", operator) print(fn.__doc__, ":", f"{a} and {b}") print("Return: ", end="") print(f"{a} {operator} {b}") print(f"Output: " + str(res)) return res return add_some_decorations return features @dec(operator="+") def add(a, b): "Addition of 2 arguments" return a + b @dec(operator="-") def sub(a, b): "Subtraction of 2 arguments" return a - b x = add(5, 2) x = sub(1, 4)
output
Function: add(5, 2) Operator: + Addition of 2 arguments : 5 and 2 Return: 5 + 2 Output: 7 Function: sub(1, 4) Operator: - Subtraction of 2 arguments : 1 and 4 Return: 1 - 4 Output: -3
First video tutorials about decorators
Second video tutorial about decorators
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame