**
The Python Tutorial读书笔记(1)—默认参数的几点需要注意的地方
**
- 在默认的函数形式参数中可以使用以前定义过的变量作为函数形式参数的默认值,具体表现见下:
i = 5
def f(arg=i):
print arg
i = 6
f()
#来源于The Python Tutorial
作为解释性语言在在定义函数f的过程中,i 已经存在了,因此绑定的是与函数在同一作用域中的变量的值,不管是全局变量还是临时变量。
- 当可变对象类型作为默认形式参数是会出现不同的差异性如下:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
#执行结果
[1]
[1, 2]
[1, 2, 3]
也就是说函数绑定了一个空的链表L,当定义函数的后,L分配了固定的地址空间,当调用函数对L进行操作后L的地址空间是没有发生变化的,而前面第一个例子中,i在函数定义的过程中绑定了i的地址空间,在后面定义的i只是一个同名的变量,测试结果如下:
def func():
i = 6
print id(6)#31826144
def tem_func(arg = i):
#print arg
print id(arg)#31826144
i = 7
print id(i)#31826120
tem_func()
i = 10
print id(i)##31826048
func()
#结果
#31826048
#31826144
#31826120
#31826144
从结果来看体现了形式参数的依赖于定义前的语句环境。形式参数绑定某一变量。
- 默认参数的位置限制与CC++相同,不过可以使用键值对来进行参数匹配。
如The Python Tutorial一样:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword