Question:
How can I make two decorators in Python that would do the following.
@makebold
@makeitalic
def say():
return "Hello"
which should return
1
<b><i>Hello</i></b>
Anwser A:
#!/usr/bin/env python
#-*-coding=utf-8-*-
def makeblod(func):
def wrap():
return "<b>" + func() + "</b>"
return wrap
def makeitalic(func):
def wrap():
return "<i>" + func() + "</i>"
return wrap
@makeblod
@makeitalic
def say():
return "Hello"
print say()
# This is the exact equivalent to
def say():
return "hello"
say = makebold(makeitalic(say))
Anwser B:
#!/usr/bin/env python
#-*-coding=utf-8-*-
def makehtml(tag=None):
def wrap(func):
def wrapped(*args, **kwargs):
return "<%s>" % tag + func() + "</%s>" % tag
return wrapped
return wrap
@makehtml("html")
@makehtml("body")
@makehtml("h1")
def say():
return "Hello"
print say()
print say
Anwser C:
#!/usr/bin/env python
#-*-coding=utf-8-*-
from functools import wraps
def makehtml(tag=None):
def wrap(func):
@wraps(func)
def wrapped(*args, **kwargs):
return "<%s>" % tag + func() + "</%s>" % tag
return wrapped
return wrap
@makehtml("html")
@makehtml("body")
@makehtml("h1")
def say():
return "Hello"
print say()
print say
[stackoverflow.com top voted python questions]
[1]how can i make a chain of function decorators
[2]functools.wraps