一、編寫可接受任意數量參數的函數:*、**
>>> def test(x, *args, y, **kwargs): ... pass ... >>> test(1, 2, 3, 4 ,5 ,5, y=9, aa=99, bb=88,cc=900) >>> test(1, 2, 3, 4 ,5 ,5, 9, aa=99, bb=88,cc=900) Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: test() missing 1 required keyword-only argument: 'y'
#以*打頭的參數只能作為最后一個位置參數出現,以**打頭的參數只能作為最后一個參數出現;*args之后仍然可以有其它的參數出現,但只能是關鍵字參數(keyword_only)
二、編寫只接受關鍵字參數的函數
>>> def test(*, x, y): ... pass ... >>> test(8, 9) Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: test() takes 0 positional arguments but 2 were given >>> test(x=9, y=8)
#星號*之后的參數都是keyword_only參數
三、函數注解
>>> def add(x:int ,y:int) ->int: ... return x + y ... add.__annotations__ {'x': <class 'int'>, 'return': <class 'int'>, 'y': <class 'int'>}
#函數注解只會保存在函數的__annotations__屬性中;因為Python中沒有類型聲明,函數注解可以用于提示
四、從函數中返回多個值:各返回值之間以逗號“,”分隔,本質上是返回一個tuple,可通過tuple解包實現返回多個值的目的
>>> def myfun(): ... return 1, 2, 3 ... >>> x, y, z = myfun() >>> x 1 >>> y 2 >>> z 3 >>> a = myfun() >>> a (1, 2, 3)
五、定義帶有默認參數的函數
默認參數只會在函數定義時被綁定一次
>>> x = 44 >>> def sample(a=x): ... print(a) ... >>> sample() 44 >>> x = 88 >>> sample() 44
默認參數的默認值通常應該是不可變對象;若設置可變對象,應參照如下方式:
>>> def test(a, b=None): ... if b is None: ... b = [] ... pass ...
六、嵌套函數
>>> def xxx(m): ... def yyy(n): ... return m + n ... return yyy ... >>> xxx(20) #可對比嵌套列表的邏輯進行理解 <function xxx.<locals>.yyy at 0x7f68c3aef0d0> >>> xxx(20)(20) #給內嵌的函數參數賦值 40
>>> def test(m): ... return lambda n: m + n #實現原理上,lambda可以理解為嵌套函數 ... >>> test(20)(20) 40
七、讓帶有N個參數的可調用對象以較少的參數形式調用
即:給一部分參數預先斌予固定值,相當于轉化成一個帶有默認值的函數
>>> def sum(a, b, c, d): ... return a + b + c + d ... >>> sum(1, 2, 3, 4) 10 >>> import functools >>> test_0 = functools.partial(sum, b=2, c=3, d=4) >>> test_0(1) 10 >>> test_0(100) 109
也可使用lambda函數實現
>>> test_1 = lambda a, b=2, c=3, d=4: sum(a, b, c, d) >>> test_1(1) 10 >>> test_1(100) 109