这是因为实参值是根据形参的位置赋给形参的,例如:def func(a, b = 5)合法,但def func(a = 5, b)就非法了。
关键实参
如果你有一些函数拥有许多参数,但你只想使用其中的几个,这时你可以通过形参名为其赋值。
这被称做关键实参——使用形参名(关键字)为函数指定实参而不是我们一直使用的通过位置指定实参。
这样做有两个优点,首先函数用起来更简单,因为我们不用操心实参的顺序了。
其次,可以只为我们感兴趣的形参赋值,如果其它参数带有默认实参值的话。
示例
1 2 3 4 5 6 7 8 9
#!/usr/bin/python # Filename: func_key.py
deffunc(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7) func(25, c=24) func(c=50, a=100)
输出
1 2 3 4
$ python func_key.py a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50
可变参数(VarArgs)
有时你可能希望编写一个可以接受任意多个形参的函数,使用星号可以帮你做到。
示例
1 2 3 4 5 6 7 8 9 10 11 12
#!/usr/bin/python # Filename: total.py
deftotal(initial=5, *numbers, **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return count
defprintMax(x, y): '''Prints the maximum of two numbers. The two values must be integers.''' x = int(x) # convert to integers, if possible y = int(y) if x > y: print(x, 'is maximum') else: print(y, 'is maximum')
printMax(3, 5) print(printMax.__doc__)
输出
1 2 3 4
$ python func_doc.py 5 is maximum Prints the maximum of two numbers. The two values must be integers.