Last active
May 15, 2018 14:33
-
-
Save tangingw/d5032e5fc30f42429f89f0beed33a80f to your computer and use it in GitHub Desktop.
Learning on Python Decorator
This file contains hidden or 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
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