.feed-links {display:none !important;} -->

Python decorators

 decorator is a function that modifies the behavior of other functions.

The decorators are useful when you want to add the same code to several existing features.

Create a python decorator

Let us take the example of a function which can only be executed if the user is "olive tree".

# coding: utf-8

user  =  "olive tree"

def  my_decorateur ( function ):

    def  other_function (): 
        print  "Action refused"

    if  user  <>  "olive tree" : 
        return  other_function

    return  function 


@mon_decorateur 
def  do_that (): 
    print  "Execution of instructions"
>>>  do_that () 
Execution  of  instructions

Let's change the value of the variable user .

user  =  "jean-louis"

Let's run the function again do_that .

>>>  do_that () 
Action  denied

Voila, we succeeded in prohibiting the execution of the function do_that if the user is not "olive tree".

Take into account the parameters

The decorator can take into account the parameters of our initial function in this way:

# coding: utf-8

def  my_decorateur ( function ):

    def  other_function ( * param ,  ** param2 ): 
        print  "Action before .............." 
        function ( * param ,  ** param2 ) 
        print  "Action after ....... ....... "

    return  other_function


@my_decorateur 
def  do_that ( v ): 
    print  "Execution of instructions % s "  %  v

Let's run the function do_that .

>>>  do_that ( "delete" ) 
Action  before  ..............  
Execution  of  delete statements  Action after ..............
  

Several decorators

It is obviously possible to assign several decorators to a function:

@ decorateur1 
@ decorateur2 
def  my_function ():

No comments:

Post a Comment