Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
2 views
in Python by (10.2k points)
edited by

Can someone tell me how to make two decorators that would do the following in python:

@makeitalic
@makebold
def say():
   return "Hey"

Result should be: 

"<i><b>Hey</b></i>"

 I just want to understand how decorators works?

P.S. - Not trying to make HTML

2 Answers

0 votes
by (2k points)
edited by

You can check the help to see how decorators work.

For your Question, check this:

from functools import wraps

def makeitalic(fn): @wraps(fn) def wrapped(*args, **kwargs): return "<i>" + fn(*args, **kwargs) + "</i>" return wrapped

def makebold(fn):

@wraps(fn) def wrapped(*args, **kwargs): return "<b>" + fn(*args, **kwargs) + "</b>" return wrapped @makeitalic @makebold def Hey(): return "Hey PC" @makeitalic @makebold def log(s): return s print Hey() # returns "<i><b>Hey PC</b></i>" print Hey.__name__ # with functools.wraps() this returns "Hey" print log('Hey') # returns "<i><b>hello</b></i>"

0 votes
by (106k points)

You can return lambdas from a decorator function:

def makebold(f): 

    return lambda: "<b>" + f() + "</b>"

def makeitalic(f): 

    return lambda: "<i>" + f() + "</i>"

@makebold

@makeitalic

def say():

    return "Hello"

print say()

You can use the following video tutorials to clear all your doubts:-

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...