当前位置:   article > 正文

python函数定义之默认值参数_def ask_ok(prompt,

def ask_ok(prompt,

python函数定义之默认值参数

默认值参数

为参数指定默认值是非常有用的方式。调用函数时,可以使用比定义时更少的参数,例如:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = 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 ValueError('invalid user response')
        print(reminder)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

该函数可以用以下方式调用:

只给出必选实参:ask_ok(‘Do you really want to quit?’)

给出一个可选实参:ask_ok(‘OK to overwrite the file?’, 2)

给出所有实参:ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)

本例还使用了关键字 in ,用于确认序列中是否包含某个值。

默认值在 定义 作用域里的函数定义中求值,所以:

i = 5

def f(arg=i):
    print(arg)

i = 6
f()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上例输出的是 5。

重要警告: 默认值只计算一次。默认值为列表、字典或类实例等可变对象时,会产生与该规则不同的结果。例如,下面的函数会累积后续调用时传递的参数:

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

print(f(1))
print(f(2))
print(f(3))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

输出结果如下:

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

不想在后续调用之间共享默认值时,应以如下方式编写函数:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L
  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/261426
推荐阅读
相关标签
  

闽ICP备14008679号