Python 函数参数使用

默认参数

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise IOError('refusenik user')
        print complaint

默认值在定义域中的函数定义的时候计算,例如:

i = 5

def f(arg=i):
    print arg

i = 6
f()

将打印5。

默认值只计算一次。这使得默认值是列表、字典或大部分类的实例时会有所不同。

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

print f(1)
print f(2)
print f(3)

这将打印:

[1]
[1, 2]
[1, 2, 3]

如果不想共享默认参数,可以设置:

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

未完待续

原文地址:https://www.cnblogs.com/S-yesir/p/4885364.html