找回密码
 立即注册
搜索
查看: 15|回复: 0

函数定义详解

[复制链接]

339

主题

0

回帖

11

积分

管理员

积分
11
发表于 前天 19:33 | 显示全部楼层 |阅读模式
函数定义支持可变数量的参数。这里列出三种可以组合使用的形式。

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

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        reply = input(prompt)
        if reply in {'y', 'ye', 'yes'}:
            return True
        if reply in {'n', 'no', 'nop', 'nope'}:
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)
该函数可以用以下方式调用:

只给出必选实参: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()
上例输出的是 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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|skypiea

GMT+8, 2026-4-17 06:40 , Processed in 0.048693 second(s), 21 queries .

Powered by skypiea

快速回复 返回顶部 返回列表