Back
Can someone tell me how to make two decorators that would do the following in python:
@makeitalic@makebolddef 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
You can check the help to see how decorators work.
For your Question, check this:
from functools import wrapsdef makeitalic(fn): @wraps(fn) def wrapped(*args, **kwargs): return "<i>" + fn(*args, **kwargs) + "</i>" return wrappeddef 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>"
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>"
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@makeitalicdef say(): return "Hello"print say()
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.
31k questions
32.8k answers
501 comments
693 users