python函数定义的时候默认参数放在哪_Python编程入门之深入了解函数定义默认参数值...

More on Defining Functions--- Default Argument Values

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, complaint='Yes or no, please!'):

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 IOError('refusenik user')

print(complaint)

This function can be called in several ways:这个函数可以几种方法被调用:

giving only the mandatory argument: ask_ok('Do you really want to quit?')

giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)

or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.这个例子中引用了关键字in.它将测试一个序列是否含有某个值.

The default values are evaluated at the point of function definition in the defining scope, so that will print 5.默认值在函数定义的范围内被赋值,所以此处将打印值5.

i = 5

def f(arg=i):

print(arg)

i = 6

f()

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

126402af9b85927646c53ec065922733.png

f895988c330fd8a3b2a654c46b91d70e.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值