Skip to content

Instantly share code, notes, and snippets.

@afaquejam
Last active August 18, 2019 15:44
Show Gist options
  • Save afaquejam/6e9b42689a4958be8706510cdc9f7178 to your computer and use it in GitHub Desktop.
Save afaquejam/6e9b42689a4958be8706510cdc9f7178 to your computer and use it in GitHub Desktop.
Python Decorators - 3
################################################
# What are decorators?
# Bascially a wrapper function, which modify the behaviour of a function, without
# changing the functionality of the original function.
# What problem do they actually solve?
# They alter the functionality of a function or a class.
#################################################
# Some original function, whose source we don't want to modify for some reason.
def get_text(name):
return "Hola {0}! Fuck you anyway!".format(name)
def p_decorate(func):
# Here, you modify the behaviour of any function, that takes a string as
# an argument and returns a string.
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
my_get_text = p_decorate(get_text)
print my_get_text("John")
#################################################
# Same fuctinality, using the @ operator
#################################################
def a_decorate(func):
def func_wrapper(name):
return "<p>{0}</p>".format(func(name))
return func_wrapper
# This means, the functionality of get_txt is modified by the a_decorate function.
@a_decorate
def get_txt(name):
return "Hola {0}! Fuck you anyway!".format(name)
print get_txt("John")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment