您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 辽阳分类信息网,免费分类信息发布

Python编程入门之深入了解函数定义默认参数值

2022/9/22 22:31:26发布59次查看
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
辽阳分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录