Python decorators!

Posts about decorators

One useful things are decorators. At the beginning can be a little intimidating and can confuse you, but are very simple to use once you get them. I made the most simple script I could make for this tutorial (code on github repository python_cheatsheet/decorator.py).

What is a decorator?

It is a function/decorator that can be used more times by different functions using simply a @ and the function name before the function that want to use the decorator

The flow chart of the usage of decorator:

This way all the other functions will use the same code in the decorator in common, saving code and organizing code better. The code is also more mantainable.

The example

# decorators

def print_it(fn):
    def show_result(a, b):
        print(f"{fn.__name__}({a},{b}) is = to {fn(a, b)}")
    return show_result


@print_it
def add(a, b):
    return a +  b


@print_it
def subt(a, b):
    print("This is subt")
    return a - b


@print_it
def mult(a, b):
    print("This is mult")
    return a * b


@print_it
def div(a, b):
    print("This is div")
    return a // b

# add(5, 4) # 9
# print("Let's go to the other one")
# subt(2, 3) # -1
div(10, 5)

output

This is div
div(10,5) is = to 2
>>>

The video


Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts