Python 默认参数

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

想象一下古埃及的沙漠,金字塔高耸入云,在这片充满神秘和历史的土地上投下长长的阴影。在这个实验中,我们冒险进入胡夫大金字塔内一个新出土的墓室。墓室墙壁上的象形文字讲述了一位失落神灵的故事,一旦用正确的咒语召唤出其化身,其力量就会恢复。据说这位神灵有赐予智慧和知识的力量,尤其是在神秘的 Python 编程艺术方面。

我们的目标是通过解决墓室中布置的 Python 谜题来解码召唤这位神灵化身所需的咒语。要做到这一点,我们必须掌握 Python 函数中默认参数的使用——这是一个与金字塔本身一样永恒的概念。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/FunctionsGroup -.-> python/default_arguments("Default Arguments") subgraph Lab Skills python/default_arguments -.-> lab-271545{{"Python 默认参数"}} end

创建带默认参数的函数

在这一步中,我们将创建一个函数,它将帮助我们解开通往神灵墓室的第一道封印。Python 函数可以有默认参数,当函数被调用时,如果没有提供特定的值,就会使用默认参数。让我们通过创建一个生成具有默认能量等级的古代咒语的函数来练习这一点。

现在,使用你喜欢的文本编辑器打开 ~/project/incantation.py,并定义一个名为 cast_spell 的函数,该函数接受两个参数:spell(字符串)和 power_level(整数,默认值为 5)。

incantation.py 中的示例代码:

def cast_spell(spell, power_level=5):
    return f"Invoking {spell} with a power level of {power_level}!"

## Test the function by calling it with and without specifying the power_level
print(cast_spell('Heka'))
print(cast_spell('Seshat', power_level=9))

运行你的代码,看看咒语是否被调用。

python3 incantation.py

预期输出:

Invoking Heka with a power level of 5!
Invoking Seshat with a power level of 9!

处理多个默认参数

接下来,我们将使用一个带有多个默认参数的函数来解开第二个封印。我们将创建一个函数,用于描述向神灵献上的祭品。

仍在 ~/project 目录中,在我们的 incantation.py 文件中添加一个名为 make_offering 的新函数,该函数将接受三个参数:food(默认值为 "grain")、incense(默认值为 "frankincense")和 gemstone(默认值为 "lapis lazuli")。

incantation.py 中的示例代码:

def make_offering(food="grain", incense="frankincense", gemstone="lapis lazuli"):
    return f"Offering {food}, {incense}, and {gemstone} to please the gods."

## Test the function with default and custom arguments
print(make_offering())
print(make_offering(food="dates", gemstone="turquoise"))

运行更新后的文件:

python3 incantation.py

预期输出:

Offering grain, frankincense, and lapis lazuli to please the gods.
Offering dates, frankincense, and turquoise to please the gods.

总结

在这个实验中,我们通过一场古埃及金字塔冒险的背景,深入探究了 Python 默认参数的强大功能。你不仅学会了定义带有默认参数的函数并根据需要进行定制,还通过将 Python 语法与埃及学的魅力相结合,驾驭了埃及神灵的魔力。

通过完成这些任务,你获得了一项宝贵的技能,这将对你编写灵活且可复用的 Python 代码大有帮助。既然你已经掌握了默认参数,那么你就准备好在 Python 的世界中揭开更多秘密了——这门语言既像金字塔一样神秘莫测,又像月光下晴朗夜空中开阔沙漠一样易于探索。