嵌套函数
Coddy Python 装饰器 课程的第 2 课,共 12 课。
在学习装饰器之前,我们需要先了解几个与 Python 函数相关的重要概念。
在 Python 中,我们可以在一个函数内部定义另一个函数,这也称为嵌套函数。
例如:
def outer_function():
print("This is the outer function.")
def inner_function():
print("This is the inner function.")
inner_function()
在这个例子中,outer_function 包含一个名为 inner_function 的嵌套函数。
调用 outer_function 时,它会先打印 "This is the outer function.",然后调用 inner_function。接着,inner_function 会打印 "This is the inner function."
请注意,只有在 outer_function 内部才能调用 inner_function。
如果你尝试在 outer_function 外部调用 inner_function,就会收到 NameError,提示 inner_function 未定义。
挑战
简单编写一个名为 greeting_generator 的函数,它接收一个姓名作为参数,并返回一条包含该姓名的问候语。
这条问候语应由一个名为 get_greeting 的嵌套函数生成。它接收姓名作为参数,并返回一个内容为 "Hello, [name]!" 的字符串。
下面是这个函数的用法示例:
>>> greeting = greeting_generator("Alice")
>>> greeting
"Hello, Alice!"
>>> greeting = greeting_generator("Bob")
>>> greeting
"Hello, Bob!"
限制条件
- 必须使用名为
get_greeting的嵌套函数来生成问候语。 - 问候语必须包含传递给
greeting_generator的姓名。
亲手试试
Python 装饰器中的所有课
自己练习: Python 在线编译器