默认参数与命名参数
Coddy 面向 C 开发者的 Python 课程 课程的第 23 课,共 48 课。
C 函数只有位置参数,没有语言层面的默认参数。C 包装函数可以显式提供常见的数量;而 Python 则可以在函数定义中表达该默认值。Python 调用者可以使用位置参数后跟关键字参数,且关键字是通过名称指定参数而不是靠位置。省略的参数会使用存储的默认值。默认值是在 def 语句执行时计算一次,而不是在每次调用时单独计算。
C:完整的 example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
int cost(int price, int quantity) { return price * quantity; }
int main(void) {
printf("%d\n", cost(6, 1));
return 0;
}Python:完整的 example.py
def cost(price, quantity=1):
return price * quantity
print(cost(quantity=3, price=6))注意差异
默认的 list 参数可能会在多次调用之间保留修改。当每次调用都需要全新的状态时,请使用 None 作为默认值,并在函数内部创建 list。同时通过位置和关键字提供同一个参数会引发 TypeError。
你的代码写在 functions.py 中。锁定的 driver.py 是入口文件,负责提供执行与检查功能,无法编辑。
挑战
入门实现 line_cost(price, quantity=1, discount=0),返回整数 price * quantity - discount。输入均为非负数,且折扣最多为乘积。驱动程序会读取 price、quantity 和 discount,先仅传入 price 调用一次,再传入两个位置参数调用一次,最后使用重新排序的关键字参数调用一次,并打印结果。
在可编辑模块中实现指定的定义,请勿包含输入或打印操作。驱动程序负责输入/输出,并可能会在新的数据上再次调用 API,而不会产生额外的输出。
Python 的默认参数和具名调用在 C 语言语法中没有直接对应的调用形式。
你的代码写在 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 在线编译器