Python 基础系列 10 - 函数的默认值参数 Function Default Parameters

有关 Function 的默认值参数,会有一些坑,初学时容易中招和疑惑,所以花点时间研究一下,加深印象。更多 Python 基础系列文章,请参考 Python 基础系列大纲

引用官网内容,主要是强调默认参数只在定义时初始化赋值一次,特别针对 mutable 可变类的默认参数有影响。

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended.

默认值参数必须在非默认值参数后,默认值参数的默认值是可以选的,可以使用默认的参数值,也可以调用时传入的 arguments 覆盖其值。

默认参数是在函数定义时就被实例化,并非在执行时。正因为这种特性,mutable 默认参数会有负面影响。

Default parameters are instantiated at the time the function is created:
● namely at function definition time and NOT at function execution time, or runtime;
● The nature of the default parameter instantiation may have adverse affects on the mutable types, e.g., lists and dictionaries used as default parameters to the function

还是通过举例来验证吧。

def f(a, L=[]):
    print(f'print default parameter L:{L}')
    L.append(a)
    return L

print(f'print f(1):{f(1)}')
print(f'print f(2):{f(2)}')
print(f'print f(3):{f(3)}')

默认参数初始值为[],随着反复调用,它的值也会变化影响后面的每次调用。

# output:
print default parameter L:[]
print f(1):[1]
print default parameter L:[1]
print f(2):[1, 2]
print default parameter L:[1, 2]
print f(3):[1, 2, 3]

覆盖默认值,这样的结果是我们所期望的。

def f(a, L=[]):
    L.append(a)
    return L

print(f(1, [1,1]))
print(f(2, [2,2]))
print(f(3, [3,3]))
# output:
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]

如果有一定要用默认值,有啥办法能返回我们所期望的结果呢?

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

print(f'print f(1):{f(1)}')
print(f'print f(2):{f(2)}')
print(f'print f(3):{f(3)}')

当使用默认参数时,重新初始化其值

# output:
print f(1):[1]
print f(2):[2]
print f(3):[3]

布置个作业,检验一下你是否真地欣赏到了默认参数的魅力,哈哈!最后输出的结果是?

def make_list(value, default = []):
    default.append(value)
    return default

def make_another_list(value, default = None):
    if default is None:
        default = []
    default.append(value)
    return default

make_list(4)
make_another_list(4)
new_list = make_list('hello') + make_another_list('world')
print(new_list)

你可能感兴趣的:(#,Python,基础系列,python,Function,默认值参数)