Skip to content

Instantly share code, notes, and snippets.

@tangingw
Last active May 15, 2018 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tangingw/d5032e5fc30f42429f89f0beed33a80f to your computer and use it in GitHub Desktop.
Save tangingw/d5032e5fc30f42429f89f0beed33a80f to your computer and use it in GitHub Desktop.
Learning on Python Decorator
def decorate_msg(func):
def wrapped(*args):
return "the answer is %f" % func(*args)
return wrapped
def filename_decorate(filename):
def new_decorate(func):
def wrapped(*args):
with open(filename, "w", newline="") as file_obj:
msg_written = "the answer is %f" % func(*args)
file_obj.write(msg_written)
return "file %s written successfully" % filename
return wrapped
return new_decorate
@filename_decorate("fireball.txt")
def add_two(num):
return num + 2
@filename_decorate("yahoo.txt")
def multiply_two(num):
return num * 2
print(add_two(9.0))
print(multiply_two(9.0))
"""Reference:
https://www.thecodeship.com/patterns/guide-to-python-function-decorators/
http://ot-note.logdown.com/posts/67571/-decorator-with-without-arguments-in-function-class-form
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment