Python Exercise: Make a chain of function decorators in Python
Write a Python program to create a chain of function decorators (bold, italic, underline etc.).
Sample Solution:
Python Code:
# Define a decorator 'make_bold' that adds bold HTML tags to the wrapped function's return value
def make_bold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
# Define a decorator 'make_italic' that adds italic HTML tags to the wrapped function's return value
def make_italic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
# Define a decorator 'make_underline' that adds underline HTML tags to the wrapped function's return value
def make_underline(fn):
def wrapped():
return "<u>" + fn() + "</u>"
return wrapped
# Apply multiple decorators (@make_bold, @make_italic, @make_underline) to the 'hello' function
@make_bold
@make_italic
@make_underline
def hello():
return "hello world"
# Print the result of the decorated 'hello' function, which adds HTML tags for bold, italic, and underline
print(hello()) ## returns "<b><i><u>hello world</u></i></b>"
Sample Output:
hello world
Explanation:
In the exercise above the code defines three decorators ('make_bold', 'make_italic', and 'make_underline') that wrap a function by adding HTML tags for bold, italic, and underline, respectively. Then, it decorates the "hello()" function by applying multiple decorators (@make_bold, @make_italic, @make_underline) in a chained manner. Finally, it prints the result of the decorated "hello()" function, which includes HTML tags for bold, italic, and underline applied to the original return value "hello world".
Pictorial presentation:
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included).
Next: Write a Python program to execute a string containing Python code.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics