Python decorator? - can someone please explain this?

前端 未结 6 961
离开以前
离开以前 2020-11-29 10:42

Apologies this is a very broad question.

The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protect

6条回答
  •  迷失自我
    2020-11-29 11:28

    First, we need to understand why we need Decorator.

    Need for decorator: We want to use the function of already built-in Library from Python which can perform our desired task.

    Problems: But problem is that we don't want exact function output. We want customized output. The trick is that we can't change the original code of the function. here decorator comes to our help.

    Solutions: Decorator takes our required function as input, wraps it in a wrapper function and does 3 things:

    1. do something before.
    2. then call the desired function().
    3. do something after.

    Overall code:

    def my_decorator(desired_function):
        def my_wrapper():
            print "do something before"   #do something before, if you want to
            desired_function()
            print "do something after"    #do something after, if you want to
        return my_wrapper
    
    desired_func = my_decorator(desired_func())   #create decorator
    desired_func()                           #calling desired_func()   
    

提交回复
热议问题