Created
April 22, 2020 03:35
-
-
Save HamdyTawfeek/bc253119b1bd9ce43bef2d0510b1027f to your computer and use it in GitHub Desktop.
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
| from functools import wraps | |
| # Our Basic Function Defn | |
| def print_name(name): | |
| print(name) | |
| print_name("jimmy") | |
| # Let's add a simple decorator to inject a greeting | |
| def add_greeting(f): | |
| @wraps(f) | |
| def wrapper(*args, **kwargs): | |
| print("Hello!") | |
| return f(*args, **kwargs) | |
| return wrapper | |
| @add_greeting | |
| def print_name(name): | |
| print(name) | |
| print_name("sandy") | |
| # Let's add some complexity in the form of a paramater | |
| def add_greeting(greeting=''): | |
| def add_greeting_decorator(f): | |
| @wraps(f) | |
| def wrapper(*args, **kwargs): | |
| print(greeting) | |
| return f(*args, **kwargs) | |
| return wrapper | |
| return add_greeting_decorator | |
| @add_greeting("what's up!") | |
| def print_name(name): | |
| print(name) | |
| print_name("kathy") | |
| # We can also pass information back to the wrapped method | |
| def add_greeting(greeting=''): | |
| def add_greeting_decorator(f): | |
| @wraps(f) | |
| def wrapper(*args, **kwargs): | |
| print(greeting) | |
| return f(greeting, *args, **kwargs) | |
| return wrapper | |
| return add_greeting_decorator | |
| @add_greeting("Yo!") | |
| def print_name(greeting, name): | |
| print(greeting) | |
| print(name) | |
| print_name("Abe") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment