DEV Community


Day 25 Of 100DaysOfCode : Python Decorators

Durga Pokharel
A mathematics student learning to code.
・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")
    return inner

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

pretty = make_pretty(ordinary)
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 func(a, b)
    return inner

def divide(a, b):

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):
printer = star(percent(printer))

Enter fullscreen mode Exit fullscreen mode

Output of this code is

Enter fullscreen mode Exit fullscreen mode

Discussion (2)

furtleo profile image
Leonardo Furtado

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

iamdurga profile image
Durga Pokharel Author

Thank you for support πŸ€—