装饰器的链式调用
Coddy Python 装饰器 课程的第 7 课,共 12 课。
你可以将多个装饰器串联起来,以修改函数的行为。要串联装饰器,只需依次应用它们,让最内层的装饰器最靠近被装饰的函数。
来看一个例子:
def make_bold(func):
def wrapper():
return "<b>" + func() + "</b>"
return wrapper
def make_italic(func):
def wrapper():
return "<i>" + func() + "</i>"
return wrapper
@make_bold
@make_italic
def hello():
return "Hello, world!"
print(hello())最终输出是:
<b><i>Hello, world!</i></b>注意,在上面的例子中,装饰器会返回函数的值。到目前为止,我们只见过执行函数但不返回其结果的装饰器!
挑战
中等编写一个名为 my_decorator 的函数,它接收一个整数参数 n,并返回一个装饰器函数。这个装饰器函数会用 n 层 HTML 标签包装给定的函数 func。最外层的标签应为 <div>,下一层应为 <p>,之后每一层都交替使用 <div> 和 <p> 标签。最内层应使用 <b> 标签包装函数的输出。
下面给出了将与 my_decorator 一起执行的代码,不要更改它!
示例:
@my_decorator(3)
def my_function(s):
return s.upper()
result = my_function("hello world")
print(result)输出:
<div>
<p>
<div>
<b>
HELLO WORLD
</b>
</div>
</p>
</div>使用换行符(
\n)来正确设置输出格式!
亲手试试
# 在这里编写代码
# 不要修改这行以下的代码
n = int(input())
@my_decorator(n)
def my_function(s):
return s.upper()
result = my_function(input())
print(result)Python 装饰器中的所有课
自己练习: Python 在线编译器