1.函数的默认参数
Python函数支持默认参数。与其他类型的语言的默认参数适用方法相同。
>>>def someFunction(message = "hello"): print(message) >>> someFunction() hello >>> someFunction("new message") new message >>>
值得注意的是,当默认值是list,dictionary或者class的时候,这样说起来可能不好理解,下面的例子可以说明这个问题
>>> def f(a, L=[]): L.append(a) return L >>> print(f(1)) [1] >>> print(f(2)) [1, 2] >>> print(f(3)) [1, 2, 3] >>>
这种情况下,我们经常很困扰,因为与原来我们对默认参数的理解方式不一样,下面的例子可以解决这个问题,使得默认参数的形式看起来跟原来一样。
>>> def f2(a, L=None): if L is None: L = [] L.append(a) return L >>> print(f2(1)) [1] >>> print(f2(2)) [2] >>> print(f2(3)) [3] >>>
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('uncooperative user') print(complaint) >>> ask_ok('Do you really want to quit?') Do you really want to quit?y True >>> ask_ok('Do you really want to quit?') Do you really want to quit?n False >>> ask_ok('Do you really want to quit?') Do you really want to quit? Yes or no, please! Do you really want to quit?y True >>> ask_ok('Do you really want to quit?') Do you really want to quit? Yes or no, please! Do you really want to quit? Yes or no, please! Do you really want to quit? Yes or no, please! Do you really want to quit? Yes or no, please! Do you really want to quit? Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> ask_ok('Do you really want to quit?') File "<pyshell#17>", line 10, in ask_ok raise IOError('uncooperative user') OSError: uncooperative user >>>
这里函数接收用户输入的内容,根据输入运行不同的代码段,并且用户可以设定交互的次数及提示的内容,这个例子很好地演示了默认参数及函数交互,并且包含了显式抛出错误的使用方法。
默认参数如果有多个时,我们需要指定其中某个参数的时候,我们可以参照下面的例子:
>>> def fun(action, type='Move'): print(action) print(type) >>> fun("Car") Car Move >>> fun("Man","Jump") Man Jump >>> def f(a,b = "b",c = "c"): print(a) print(b) print(c) >>> f("this is a",c = "this is c") this is a b this is c >>>
3.Lambda表达式的支持
Python有一类函数可以返回Lambda表达式,就像一个函数返回另一个函数。
>>>def make_incrementor(n): return lambda x: x + n </span><span style="font-family:Microsoft YaHei;"><span class="n">f</span> <span class="o">=</span> <span class="n">make_incrementor</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span> >>> f(0) 42 >>> f(1) 43
这里返回一个表达式,f 存储了这个表达式,即 f 等同于一个函数:
def fun(x): return x + 42