DEV Community

loading...

Day 25 Of 100DaysOfCode : Python Decorators

iamdurga profile image Durga Pokharel ・2 min read

This is my 25th day of #100DaysOfCode and Python. Today I am not able to give my time more than 2 hours. Because of my own personal work. So I learned something about python decorators. And Tried to do some code on it.

Some of the code which I practice today and tried to write are given below.

Some Simple Code On Python Decorators

While I studied I learned that python has a interesting features called decorators to add functionality to an existing code. This is also called meta programming because a part of the program tried to modify another part of program.

def make_pretty(func):
    def inner():
        print("I got decorated")
        func()
    return inner


def ordinary():
    print("I am ordinary")

pretty = make_pretty(ordinary)
pretty()
Enter fullscreen mode Exit fullscreen mode

When this program run its output is

I got decorated
I am ordinary
Enter fullscreen mode Exit fullscreen mode

In the above code make_pretty is decorator, ordinary got decorated and returned function was given by the name preety.

def smart_divide(func):
    def inner(a, b):
        print("I am going to divide", a, "and", b)
        if b == 0:
            print("Whoops! cannot divide")
            return

        return func(a, b)
    return inner


@smart_divide
def divide(a, b):
    print(a/b)

divide(2,0)
Enter fullscreen mode Exit fullscreen mode

Above function is the example of decorator with parameter. Here a and b are two parameter .

Here is some other example of decorators,

def printer(text):
    print(text)
printer = star(percent(printer))

printer('Durga')
Enter fullscreen mode Exit fullscreen mode

Output of this code is

******************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Durga
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
******************************
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

pic
Editor guide
Collapse
furtleo profile image
Leonardo Furtado

Keep going, we're going along with u :)

Collapse
iamdurga profile image
Durga Pokharel Author

Thank you for support 🤗