Last active
November 30, 2019 16:21
-
-
Save Taiiwo/ce6754be2e32b92d7fe6706fb3ed9887 to your computer and use it in GitHub Desktop.
A simple file giving examples for creating decorator functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# decorators are just shorthand for passing functions as arguments to other functions | |
# They are called decorators as code can be run before and after the supplied | |
# function is run (if at all). A good use for decorator functions is adding | |
# callback hooks for your applications. The decorator functions take the | |
# supplied function and store it to be run at the right time | |
# There are two types of decorators: regular decorator and callable decorators | |
# regular decorators take the function it's decorating as an argument | |
# this is best if no extra arguments need to be given in the decoration process | |
def decorator(decorated_function): | |
print("hello") | |
decorated_function() | |
print("!") | |
@decorator | |
def world(): | |
print("world") | |
# callable decorators return a function that is called once returned | |
# this is userful if you need to pass arguments to the decoration process | |
def callable_decorator(before_text): | |
# define returned function | |
def decorate(decorated_function): | |
# execute decorated | |
decorated_function() | |
# do things after decoration here | |
print("!") | |
# do things before executing the returned function here | |
print(before_text) | |
# returned decorate function | |
return decorate | |
@callable_decorator("hello") | |
def world_2(): | |
print("world") | |
""" | |
hello # line 8 | |
world # line 14 | |
! # line 10 | |
hello # line 26 | |
world # line 32 | |
! # line 24 | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment