Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to make a chain of function decorators in Python?

I have the following code

def hello():
    return "hello world"
print hello()

How do I wrap the above function using decorators to make the output bold and italic?


1 Answer
Rajendra Dharmkar

Decorators are “wrappers”, which allow us to execute code before and after the function they decorate without modifying the function itself.

The given code can be wrapped in a chain of decorators as follows.

def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped
def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped
@makebold
@makeitalic
def hello():
    return "hello world"
print hello()

OUTPUT

C:/Users/TutorialsPoint1/~.py
<b><i>hello world</i></b>

If this html code is executed as in the link given below we get the output  as bold and italicised 'hello world'

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.