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

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

def say():
   return "Hey"

Result should be: 


 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>"



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

Browse Categories