美文网首页
4.7.1. Default Argument Values

4.7.1. Default Argument Values

作者: 赵敏是程序媛 | 来源:发表于2019-08-28 08:46 被阅读0次

4.7. More on Defining Functions

It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined.

使用一系列的参数来定义函数是可能的。下面有三种形式,它们可以组合使用。

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

最有用的形式是为一个或者多个参数指定一个默认值。它创建了这样的一个函数,函数可以使用比定义的允许的参数少的参数个数。例如:

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)

This function can be called in several ways:

这个函数可以以几种方式调用:

[if !supportLists]· [endif]

giving only the mandatory argument:

只给出强制参数:

 ask_ok('Do you really want to quit?')

[if !supportLists]· [endif]

giving one of the optional arguments:

给出一个可选参数:

 ask_ok('OK to overwrite the file?', 2)

[if !supportLists]· [endif]

or even giving all arguments: 

或者给出全部的参数:

ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

[if !supportLists]· [endif]

This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.

这个例子也介绍了in关键字。它测试了一个序列是个包含一个确定的值。(译者说,比如说2是否在序列0-5中。)

The default values are evaluated at the point of function definition in the defining scope, so that

默认值在定义范围内的函数定义处被计算,因此下面的例子输出5,而非6(译者说,也就是参数值在函数定义前给出了,后面再修改没用,还是用的函数定义前的参数值。)

i = 5

def f(arg=i):

    print(arg)

i = 6

f()

will print 5.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

重要警告:默认值只计算一次。当默认值是一个可变对象(如列表、字典或大多数类的实例)时,情况就不一样了。例如,下面的函数累积在后续调用时传递给它的参数:

def f(a, L=[]):

    L.append(a)

    return L

print(f(1))

print(f(2))

print(f(3))

This will print

[1]

[1, 2]

[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

如果你不想在后续调用之间共享默认值,你可以像下面一样写函数:

def f(a, L=None):

    if L is None:

        L = []

    L.append(a)

    return L

相关文章

网友评论

      本文标题:4.7.1. Default Argument Values

      本文链接:https://www.haomeiwen.com/subject/mywuectx.html