Python - 新手问题 - 什么是“提供可选参数”?
这段代码是干什么的呢?
它给了一个可选的参数:
ask_ok('可以覆盖这个文件吗?', 2)
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)
可以查看这个教程:
http://docs.python.org/py3k/tutorial/controlflow.html#default-argument-values
3 个回答
1
这是一个函数。
如果你正在学习Python,我建议你先读一本好的书,比如《学习Python》。从简单的教程开始,多读一些。读完之后再继续读更多的内容。Python是一门很适合初学者的美丽语言。有时候,像我一样,你可能会想到其他语言,但坚持用Python,你会取得不错的成果。
4
在Python中,有几种类型的参数:
- 位置参数和关键字参数
- 命名参数和任意参数
在Python中,函数的参数就像是给变量赋值的操作,也就是说,参数会被分配到函数内部的局部命名空间中。
如果你有这样的声明:
def some_func(pos_arg1, pos_arg2, kw_arg1=1, kw_arg2='test'):
print "postional arg 1 =", pos_arg1
print "postional arg 2 =", pos_arg2
print "keyword arg 1 =", kw_arg1
print "keyword arg 2 =", kw_arg2
位置参数是必须的,会按照给定的顺序进行赋值,而关键字参数是可选的,可以随意顺序调用——如果没有提供,命名的关键字参数会使用默认值(在这个例子中是1和'test')。到这里为止:
>>> some_func(1) # positional arguments are mandatory
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: some_func() takes at least 2 arguments (1 given)
>>> some_func(1, 2) # this is ok
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 1
keyword arg 2 = test
>>> some_func(1, 2, 3) # this is also ok, keyword args may work like positional
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 3
keyword arg 2 = test
>>> some_func(1, 2, 3, 4) # this is also ok, keyword args may work like positional
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 3
keyword arg 2 = 4
>>> some_func(1, 2, kw_arg2=3) # kyword arguments may be given in any order
postional arg 1 = 1
postional arg 2 = 2
keyword arg 1 = 1
keyword arg 2 = 3
有一个关于未声明参数的问题:
>>> some_func(1, 2, 3, 4, 5)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: some_func() takes at most 4 arguments (5 given)
但是你可以使用特殊的形式*
和**
来接受任意数量的参数:
>>> def some_func(pos_arg1, pos_arg2, *args, **kw_args):
... print "postional arg 1 =", pos_arg1
... print "postional arg 2 =", pos_arg2
... print "other positional orgs =", args
... print "other keyword args =", kw_args
...
>>> some_func(1, 2, 3, 4, 5) # any number of arguments
postional arg 1 = 1
postional arg 2 = 2
other positional orgs = (3, 4, 5)
other keyword args = {}
>>> some_func(1, 2, a=3, x=4, y=5) # * and ** are optional
postional arg 1 = 1
postional arg 2 = 2
other positional orgs = ()
other keyword args = {'a': 3, 'x': 4, 'y': 5}
>>> some_func(1, 2, 'banana', 'orange', 'apple', a=3, x=4, y=5)
postional arg 1 = 1
postional arg 2 = 2
other positional orgs = ('banana', 'orange', 'apple')
other keyword args = {'a': 3, 'x': 4, 'y': 5}
>>>
*
参数会作为位置参数的元组出现,而**
则会变成关键字参数的字典。
你可以把这些参数混合在一起,但有一个规则:所有的关键字参数必须在位置参数之后声明,所有的任意参数必须在命名参数之后。
2
将 retries
设置为 2,并把 complaint
保持在默认值 'Yes or no, please!'。在函数定义的第一行,选项参数的顺序是很重要的。