DEV Community

Durga Pokharel
Durga Pokharel

Posted on

Day 25 Of 100DaysOfCode : Python Decorators

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

Day 25 of #100DaysOfCode and #Python
* Python functions , Argument and Parameter
* Python Higher Order Function
* Python Decorators
* Some Simple Code On Python Decorators Tried To Learn Today#100DaysOfCode ,#CodeNewbie ,#beginner ,#Python pic.twitter.com/t302xx1TlK

— Durga Pokharel (@mathdurga) January 18, 2021

Top comments (2)

Collapse
 
furtleo profile image
Leonardo Furtado

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

Collapse
 
iamdurga profile image
Durga Pokharel

Thank you for support 🤗