#Python 函数的默认参数
在创建函数时,可以给某些参数设置默认值。当调用函数时,如果没有传入这些参数,对应的默认值就会被自动使用。这种机制使函数更灵活、可选参数更方便。
示例:
# 防御力默认为 0
def attack(attack_power:float, defense_power:float=0) -> None:
# damage 是 attack 函数内的局部变量
damage:float = attack_power * ( 1 - defense_power / (defense_power + 100))
# 返回伤害
return damage
print("伤害为", attack(100)) # 防御力不传递实际参数,使用默认值
print("伤害为", attack(100, 10)) # 防御力传递实际参数 10
defense_power:float=0
使得 defense_power
是一个可选参数。
当未传入 defense_power
时,使用默认值 0,公式中计算为 100% 伤害。
传入 10 时,伤害将被稍微抵消。
拥有默认值的参数必须放在参数列表的最后面,否则会报错。
#注意事项
参数的默认值应当使用 不可变类型,默认值只会在函数定义时初始化一次。 如果使用 可变类型,函数在多次调用时,该参数会共用同一份实体,互相影响。
错误示范:
def append_item(item, container=[]):
'''
向容器中添加一项元素
:param item: 要添加的元素
:param container: 被添加的容器,默认为空容器
:return: 添加元素后的容器
'''
container.append(item)
return container
# 首次调用
container1 = append_item("apple")
print(container1) # ['apple']
# 第二次调用
container2 = append_item("banana")
print(container2) # ['apple', 'banana']
# 修改 container2 也会修改参数默认值
container2[0] = 'watermelon'
# 第三次调用
container3 = append_item("strawberry")
print(container3) # ['watermelon', 'banana', 'strawberry']
在这个错误的示例中,原本期望不传递 container
参数时,创建一个空容器并加入 item
。
但实际上,container
的默认值只在定义函数时初始化一次,首次调用 append_item("apple")
后就被修改为了 ['apple']
。
第二次调用时,是向 ['apple']
中添加 'banana'
,因此得到的是 ['apple', 'banana']
而不是 ['banana']
。
并且外部的变量 container1
和 container2
都引用了参数 container
的默认值。
因此,在执行 container2[0] = 'watermelon'
时,container
的默认值被修改为了 ['watermelon', 'banana']
。
从而导致第三次调用得到了 ['watermelon', 'banana', 'strawberry']
。