Python的函数是可以给参数指定默认值的:
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = raw_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
参数的默认值也可以是一个表达式。比如:
i = 5
def f(arg=i):
print arg
i = 6
f()
这也引出了另一个问题。参数的默认值只计算一次。如果默认值是一个可变对象的话,那么这个对象只被初始化一次,并在以后的函数调用中被复用:
>>> def f(a, L=[]): ... L.append(a) ... return L ... >>> print f(1) [1] >>> print f(2) [1, 2] >>> print f(3) [1, 2, 3]
|