Files
Python_CookBook_repo/7.函数/5.定义带有默认参数的函数.py
2025-09-10 16:12:45 +08:00

38 lines
1.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 定义函数时,如果想要传入可选的参数,可以给参数加上默认值
def span(a, b=42):
print(a, b)
span(1)
span(1, 2)
# 如果给参数指定默认值为None那么该参数就可以传入可变容器
def span_v2(a, b=None):
print(a, b)
span_v2(1, [1, 2])
# 但是如果你不想设置一个默认值如果b没有传入参数那就提示那么你需要给一个obj
_no_value = object()
def span_v3(a, b=_no_value):
if b is _no_value:
print("no b")
span_v3(1)
# 注意,函数的默认参数只会在函数首次被调用的时候绑定一次,函数第一次被调用后默认参数就不可变了
x = 3
def su_ka(a = x):
print(a)
su_ka(1)
x = 4
su_ka()
# 不要用【】这种地址型数据做默认参数,因为它真的可以在过程中被修改
x = []
def su_ka(a = x):
print(a)
su_ka()
x.append(1)
su_ka()
# 上面使用object作为空参数传入也有这方面的考量因为用户的输入是不可预知的而obj几乎不可能被用户创建