Red Security

Full Version: Python 2.9: Decorators
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[Image: BFMMlbcQvml9HSqXcvNp]
Decorators:
In today’s thread we will talk about decorators. They are very useful functions. They are used to change the functionality of a function without actually changing its code. These functions modify other functions. Let's code it for better understanding.

Code:
def decorators(f):
    def printSomething():
        print("Executing function")
        f()
        print("Execution completed")

    return printSomething

def summ():
    print("Function called")

summ = decorators(summ)
summ()

So it is a simple example of decorators as we discussed in the function thread that functions can take other functions as arguments and can also return them. We are doing the same thing here. We have created a function named decorator. We passed a function through it then we created another function which executes the first line and then function f  which is actually in this program named summ and the decorator function returns us printSomething function. But if you are wondering, there is another way that we can call decorator functions. Then you are right we can replace
summ = decorators(summ)

Just what ever function you are using as argument write it like this

Code:
def decorators(f):
    def printSomething():
        print("Executing function")
        f()
        print("Execution completed")

    return printSomething
@decorators
def funct2():
    print("Function called")
funct2()

So it was a very simple example that you can understand easily. So the question arises why we use these decorators? or what is the use of it? So the answer is, let's suppose if you want to do a similar task with many functions you create a decorator function as a blueprint. So now we can call the decor function to any function we want just write the name of the function with the “@” sign above the function on which you want to apply decorators.

Code:
def decor(func):
    def wrap():
        print("============")
        func()
        print("============")
    return wrap

@decor
def print_text():
    print("Hello world!")

print_text();
@decor
def who_is_covid():
    print("Covid is a disease")

who_is_covid()


Quote:So you can use it with any number of functions you want and a function can have more than one decorator.


That’s it for now. See you in next post.


"Keep Good care of your Health
Allah Hafiz and Good Bye Till the next post"