默认值与命名参数
Coddy 面向 C++ 开发者的 Python 课程 课程的第 23 课,共 48 课。
Python 调用可以通过位置或参数名称绑定参数。cost(quantity=3, price=4) 通过名称而非顺序绑定;C++ 没有等价的普通命名参数调用语法。默认值可以填充省略的参数。Python 在执行 def 时对默认表达式求值,而 C++ 的默认参数表达式则是在使用它们的函数调用处求值。因此,Python 中可变的默认列表会在多次调用之间被重复使用。当每次调用都需要独立的状态时,优先使用 None 作为默认值,并在函数内部创建一个新列表。
C++17 摘录:main 内部
可运行的配套程序中提供了标准库头文件。
auto cost = [](int price, int quantity = 1) { return price * quantity; };
std::cout << cost(4) << '\n' << cost(4, 3) << '\n';Python
def cost(price, quantity=1):
return price * quantity
print(cost(4))
print(cost(quantity=3, price=4))迁移陷阱
同时通过位置和关键字传递同一个值会引发 TypeError。关键字参数不会覆盖先前的绑定。
在可编辑的 Python 模块中实现以下任务。被锁定的 driver.py 提供运行和检查。请保留指定的导入和 API 名称。
挑战
入门实现 line_cost(price, quantity=1, discount=0)。将 price * quantity - discount 作为整数返回。输入均为非负整数,且折扣绝不会超过乘积。请勿打印或读取输入。被锁定的驱动代码会在三行中分别读取 price、quantity 和 discount。它会分别仅传入 price、传入两个位置参数、以及按不同顺序指定所有参数名来调用你的函数。它会将这三个结果打印在独立的行中。
你的函数定义写在 functions.py 中。被锁定的 driver.py 会导入它们,并处理提供的输入/输出和检查。你不需要修改驱动代码。
亲手试试
from functions import line_cost
price = int(input())
quantity = int(input())
discount = int(input())
print(line_cost(price))
print(line_cost(price, quantity))
print(line_cost(discount=discount, price=price, quantity=quantity))
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 Python 课程中的所有课
自己练习: Python 在线编译器