约 935 字
约 5 分钟
在调用函数时,实际参数既可按顺序传递,也可按名称传递,例如:
# 创建函数
def attack(attack_power:float, defense_power:float):
# 计算伤害
damage:float = attack_power * ( 1 - defense_power / (defense_power + 100))
print(f"造成了 {damage} 点伤害")
# 按顺序传递
attack(100, 10)
# 按名称传递,不需要遵守顺序
attack(defense_power=10, attack_power=100)
Loading...
这样按名称传递的参数称为 关键字参数。
关键字参数必须在实际参数列表的末尾,否则会有歧义。例如:
# 创建函数
def attack(attack_power:float, defense_power:float):
# 计算伤害
damage:float = attack_power * ( 1 - defense_power / (defense_power + 100))
print(f"造成了 {damage} 点伤害")
# 先传递关键字参数,后面的 100 到底是第一个参数还是第二个参数?
attack(defense_power=10, 100)
Loading...
可以通过 /
和 *
分割参数列表,在 /
之前的参数只能按顺序传递,在 *
之后的参数只能按名称传递。
# pos1 和 pos2 只能按顺序传递
# kwd1 和 kwd2 只能按名称传递
# pos_or_kwd 既可按顺序传递,也可以按名称传递
def func(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
pass
创建于 2025/5/5 22:33:06
更新于 2025/5/6 00:51:08