Python Decorators

Decorators are a way to change, enhance or alter in any way how a function works.

Decorators are defined with the @ symbol followed by the decorator name, just before the function definition.

Example:

@logtime
def hello():
    print('hello!')

This hello function has the logtime decorator assigned.

Whenever we call hello(), the decorator is going to be called.

A decorator is a function that takes a function as a parameter, wraps the function in an inner function that performs the job it has to do, and returns that inner function. In other words:

def logtime(func):
    def wrapper():
        # do something before
        val = func()
        # do something after
        return val
    return wrapper


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

Decorators are a way to change, enhance or alter in any way how a function works.

Decorators are defined with the @ symbol followed by the decorator name, just before the function definition.

Example:

@logtime
def hello():
    print('hello!')

This hello function has the logtime decorator assigned.

Whenever we call hello(), the decorator is going to be called.

A decorator is a function that takes a function as a parameter, wraps the function in an inner function that performs the job it has to do, and returns that inner function. In other words:

def logtime(func):
    def wrapper():
        # do something before
        val = func()
        # do something after
        return val
    return wrapper


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-01-18T05:00:00+00:00) Python Decorators. Retrieved from https://www.scien.cx/2021/01/18/python-decorators/

MLA
" » Python Decorators." flaviocopes.com | Sciencx - Monday January 18, 2021, https://www.scien.cx/2021/01/18/python-decorators/
HARVARD
flaviocopes.com | Sciencx Monday January 18, 2021 » Python Decorators., viewed ,<https://www.scien.cx/2021/01/18/python-decorators/>
VANCOUVER
flaviocopes.com | Sciencx - » Python Decorators. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/01/18/python-decorators/
CHICAGO
" » Python Decorators." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/01/18/python-decorators/
IEEE
" » Python Decorators." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/01/18/python-decorators/. [Accessed: ]
rf:citation
» Python Decorators | flaviocopes.com | Sciencx | https://www.scien.cx/2021/01/18/python-decorators/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.