[Python] – What is @something above any method ?

The name of this is decorator. Normally you will see @staticmethod and @classmethod. This annotations call a function in your method.

Definition by python documentation : “The @decorator notation is simply a special syntax to call an existing function, passing the new function as an argument, and use the return value to replace the new function.

You can make your own decorators too. 😛

Example for you understand how to it’s work:

#CODE:
def mydecorator(fn):
    print('- My first decorator is defined')
    def wrapped():
        print('- Do something before run %s' % fn.__name__)
        fn()
        print('- Do something after run %s' % fn.__name__)
    return wrapped
 
@mydecorator
def my_func_with_my_decorator():
    print('Here is my code !!!!')
 
my_func_with_my_decorator()

#CONSOLE RESULT:

- My first decorator is defined
- Do something before run my_func_with_my_decorator
Here is my code !!!!
- Do something after run my_func_with_my_decorator

Screen Shot 2016-03-24 at 12.40.11 AM

+Info : http://pythoncentral.io/python-decorators-overview/

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s