多類(lèi)型傳值和冗余參數(shù)
- 多類(lèi)型傳參
In [1]: def fun(x, y):
...: return x + y
...:
In [2]: fun(1, 5)
Out[2]: 6
In [3]: t = (1, 5)
In [4]: fun(t)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-21f7b4b850d7> in <module>()
----> 1 fun(t)
TypeError: fun() takes exactly 2 arguments (1 given)
In [5]: fun(*t)
Out[5]: 6
In [6]: w = [1, 5]
In [7]: fun(*w)
Out[7]: 6
In [8]: def sum(x, y, z):
...: return x + y + z
...:
In [9]: sum(10, *t)
Out[9]: 16
In [10]: sum(10, *w)
Out[10]: 16
In [11]: sum(*t, 10)
File "<ipython-input-11-ccfcd859f3aa>", line 1
sum(*t, 10)
SyntaxError: only named arguments may follow *expression
In [12]: sum(*(10, 1, 5))
Out[12]: 16
In [13]: sum(*[10, 1, 5])
Out[13]: 16
In [20]: dic = {'x':1, 'y':3, 'z':5}
In [21]: sum(**dic)
Out[21]: 9
- 冗余參數(shù)
- 向函數(shù)傳元組和字典
- 處理多余實(shí)參
- def fun(x, y, *args, **kwargs)
In [15]: def fun(x, *args, **kwargs):
...: print x
...: print args
...: print kwargs
...:
In [16]: fun()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-d9f830ba61f1> in <module>()
----> 1 fun()
TypeError: fun() takes at least 1 argument (0 given)
In [17]: fun(3)
3
()
{}
In [18]: fun('a')
a
()
{}
In [27]: fun('a', 2, ['b', 3])
a
(2, ['b', 3])
{}
In [28]: fun([1, 2], 'a', 2, ['b', 3])
[1, 2]
('a', 2, ['b', 3])
{}
In [29]: dic
Out[29]: {'x': 1, 'y': 3, 'z': 5}
In [30]: fun(dic, ['a', ('b', 3), 5], ('x', 2), 9)
{'y': 3, 'x': 1, 'z': 5}
(['a', ('b', 3), 5], ('x', 2), 9)
{}
In [31]: dic2 = {'a':6, 'b':7, 'c':8}
In [32]: fun(dic, dic2)
{'y': 3, 'x': 1, 'z': 5}
({'a': 6, 'c': 8, 'b': 7},)
{}
In [39]: fun(dic, **dic2)
{'y': 3, 'x': 1, 'z': 5}
()
{'a': 6, 'c': 8, 'b': 7}
In [42]: fun(dic, dic, *t, *w, **dic2)
File "<ipython-input-42-ea2cb6c1864b>", line 1
fun(dic, dic, *t, *w, **dic2)
^
SyntaxError: invalid syntax
In [43]: fun(dic, dic, *t, **dic2)
{'y': 3, 'x': 1, 'z': 5}
({'y': 3, 'x': 1, 'z': 5}, 1, 5)
{'a': 6, 'c': 8, 'b': 7}
In [44]: fun(1, 'a', [1, 2], *t, g=6, j=8, **dic2)
1
('a', [1, 2], 1, 5)
{'a': 6, 'c': 8, 'b': 7, 'g': 6, 'j': 8}
函數(shù)的遞歸調(diào)用
- 必須有最后的默認(rèn)結(jié)果,如 if n == 0
- 遞歸參數(shù)必須向默認(rèn)結(jié)果收斂阳掐,如 factorial(n-1)
# 1) 使用循環(huán)實(shí)現(xiàn)階乘函數(shù)
In [45]: def factorial(n):
...: f = 1
...: for i in range(1, n+1):
...: f *= i
...: return f
...:
In [46]: factorial(4)
Out[46]: 24
# 2) 使用遞歸實(shí)現(xiàn)階乘函數(shù)
In [47]: def factorial(n):
...: if n == 0:
...: return 1
...: else:
...: return n * factorial(n-1)
...:
In [48]: factorial(4)
Out[48]: 24