Python_函數(shù)
在我們有面向對象思想后,會更加容易的理解。所以函數(shù)的章節(jié)內(nèi)容會較為精簡。
調用函數(shù)
Python 為我們內(nèi)置了很多有用的函數(shù),我們可以直接調用。
要調用一個函數(shù),需要知道函數(shù)的名稱和參數(shù)。關于內(nèi)置函數(shù)我們可以參看 官方文檔 。我們在這里使用 abs()
來舉例:
具體使用方式可以參考 官方文檔 或者 使用 help(abs)
來查看使用方法。
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n7" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> abs(100)
100
abs(-20)
20
abs(12.34)
12.34</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n9" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> abs(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n11" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> abs('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n14" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> int('123')
123
int(12.34)
12
float('12.34')
12.34
str(1.23)
'1.23'
str(100)
'100'
bool(1)
True
bool('')
False</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n17" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> a = abs # 變量a指向abs函數(shù)
a(-1) # 所以也可以通過a調用abs函數(shù)
1</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n21" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def my_abs(x):
if x >= 0:
return x
else:
return -x
?</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n25" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def nop():
pass</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n30" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n33" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">import math
?
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
x, y = move(100, 100, 60, math.pi / 6)
print(x, y)
151.96152422706632 70.0</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n35" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> r = move(100, 100, 60, math.pi / 6)
print(r)
(151.96152422706632, 70.0)</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n39" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def power(x,y)
print(x,y)
power(2,5)
2 5
power(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: power() missing 1 required positional argument: 'y'</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n41" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def power(x,y = 3)
print(x,y)
power(2,5)
2 5
power(2)
2 3
power(2,y = 5)
2 5</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n45" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n47" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> calc(1, 2)
5
calc()
0</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n50" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> nums = [1, 2, 3]
calc(*nums)
14</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="python" cid="n53" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: normal; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)</pre>
遺憾的是,大多數(shù)編程語言沒有針對尾遞歸做優(yōu)化,Python 解釋器也沒有做優(yōu)化,所以,即使把上面的fact(n)
函數(shù)改成尾遞歸方式,也會導致棧溢出。
尾遞歸調用時,如果做了優(yōu)化,棧不會增長,因此,無論多少次調用也不會導致棧溢出。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n92" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">===> fact_iter(5, 1)
===> fact_iter(4, 5)
===> fact_iter(3, 20)
===> fact_iter(2, 60)
===> fact_iter(1, 120)
===> 120</pre>
fact(5)
對應的fact_iter(5, 1)
的調用如下:
可以看到,return fact_iter(num - 1, num * product)
僅返回遞歸函數(shù)本身,num - 1
和num * product
在函數(shù)調用前就會被計算,不影響函數(shù)調用。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n89" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">**def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)**</pre>
尾遞歸是指,在函數(shù)返回的時候,調用自身本身,并且,return 語句不能包含表達式。這樣,編譯器或者解釋器就可以把尾遞歸做優(yōu)化,使遞歸本身無論調用多少次,都只占用一個棧幀,不會出現(xiàn)棧溢出的情況。
尾遞歸
解決遞歸調用棧溢出的方法是通過尾遞歸優(yōu)化,事實上尾遞歸和循環(huán)的效果是一樣的,所以,把循環(huán)看成是一種特殊的尾遞歸函數(shù)也是可以的。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n85" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> fact(1000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in fact
...
File "<stdin>", line 4, in fact
RuntimeError: maximum recursion depth exceeded in comparison</pre>
使用遞歸函數(shù)需要注意防止棧溢出。在計算機中,函數(shù)調用是通過棧(stack)這種數(shù)據(jù)結構實現(xiàn)的,每當進入一個函數(shù)調用,棧就會加一層棧幀,每當函數(shù)返回,棧就會減一層棧幀。由于棧的大小不是無限的,所以,遞歸調用的次數(shù)過多,會導致棧溢出。可以試試fact(1000)
:
遞歸函數(shù)的優(yōu)點是定義簡單,邏輯清晰。理論上,所有的遞歸函數(shù)都可以寫成循環(huán)的方式,但循環(huán)的邏輯不如遞歸清晰。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n82" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">**>>> fact(1)
1
fact(5)
120
fact(100)
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000**</pre>
在輸出:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n80" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">def fact(n):
if n==1:
return 1
return n * fact(n - 1)</pre>
在函數(shù)內(nèi)部,可以調用其他函數(shù)。如果一個函數(shù)在內(nèi)部調用自身本身,這個函數(shù)就是遞歸函數(shù)。
遞歸函數(shù)
所以,對于任意函數(shù),都可以通過類似func(*args, **kw)
的形式調用它,無論它的參數(shù)是如何定義的。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n76" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">**>>> args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, *kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}
args = (1, 2, 3)
kw = {'d': 88, 'x': '#'}
f2(args, kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}</pre>
最神奇的是通過一個 tuple 和 dict,你也可以調用上述函數(shù):
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n74" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">**def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)</pre>
例:
在 Python 中定義函數(shù),可以用必選參數(shù)、默認參數(shù)、可變參數(shù)、關鍵字參數(shù)和命名關鍵字參數(shù),這 5 種參數(shù)都可以組合使用。但是請注意,參數(shù)定義的順序必須是:必選參數(shù)、默認參數(shù)、可變參數(shù)、命名關鍵字參數(shù)和關鍵字參數(shù)。
參數(shù)組合
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n70" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">*def person(name, age, city, job):
# 缺少 ,city和job被視為位置參數(shù)
pass</pre>
使用命名關鍵字參數(shù)時,要特別注意,如果沒有可變參數(shù),就必須加一個*
作為特殊分隔符。如果缺少*
,Python 解釋器將無法識別位置參數(shù)和命名關鍵字參數(shù):
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n68" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> person('Jack', 24, 'Beijing', 'Engineer')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: person() takes 2 positional arguments but 4 were given</pre>
命名關鍵字參數(shù)必須傳入?yún)?shù)名,這和位置參數(shù)不同。如果沒有傳入?yún)?shù)名,調用將報錯:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n66" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">*def person(name, age, args, city, job):
print(name, age, args, city, job)</pre>
如果函數(shù)定義中已經(jīng)有了一個可變參數(shù),后面跟著的命名關鍵字參數(shù)就不再需要一個特殊分隔符*
了:
和關鍵字參數(shù)**kw
不同,命名關鍵字參數(shù)需要一個特殊分隔符*
,*
后面的參數(shù)被視為命名關鍵字參數(shù)。
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n63" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">*def person(name, age, , city, job):
print(name, age, city, job)</pre>
如果要限制關鍵字參數(shù)的名字,就可以用命名關鍵字參數(shù)。
對于關鍵字參數(shù),函數(shù)的調用者可以傳入任意不受限制的關鍵字參數(shù)。至于到底傳入了哪些,就需要在函數(shù)內(nèi)部通過kw
檢查。
命名關鍵字參數(shù)
注意kw
獲得的 dict 是extra
的一份拷貝,對kw
的改動不會影響到函數(shù)外的extra
和可變參數(shù)一樣如果我們要傳遞一個 dict 只需要在之前加上**
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n57" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}</pre>
當然,也可以傳入任意個數(shù)關鍵字:
<pre spellcheck="false" class="md-fences mock-cm md-end-block" lang="python" cid="n55" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; margin-top: 0px; margin-bottom: 20px; font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; white-space: pre-wrap; background-color: rgb(51, 51, 51); position: relative !important; padding: 10px 10px 10px 30px; width: inherit; background-position: initial initial; background-repeat: initial initial;">>>> person('Michael', 30)
name: Michael age: 30 other: {}</pre>
函數(shù)person
除了必選參數(shù)name
和age
外,還接受關鍵字參數(shù)kw
。在調用該函數(shù)時,可以只傳入必選參數(shù):
關鍵字參數(shù)就比較厲害了,可變參數(shù)允許你傳入 0 個或任意個參數(shù),這些可變參數(shù)在函數(shù)調用時自動組裝為一個 tuple。而關鍵字參數(shù)允許你傳入 0 個或任意個含參數(shù)名的參數(shù),這些關鍵字參數(shù)在函數(shù)內(nèi)部自動組裝為一個 dict。請看示例:
關鍵字參數(shù)
這種寫法當然是可行的,問題是太繁瑣,所以 Python 允許你在 list 或 tuple 前面加一個*
號,把 list 或 tuple 的元素變成可變參數(shù)傳進去:
之前有說過是將數(shù)據(jù)封裝在 tuple 中去,可是我如果要傳遞 list 數(shù)據(jù)怎么辦呢,難道要 calc(list[0], list[1], list[2])
這個樣子的傳遞數(shù)據(jù)嗎?
定義可變參數(shù)和定義一個 list 或 tuple 參數(shù)相比,僅僅在參數(shù)前面加了一個*
號。在函數(shù)內(nèi)部,參數(shù)numbers
接收到的是一個 tuple,因此,函數(shù)代碼完全不變。但是,調用該函數(shù)時,可以傳入任意個參數(shù),包括 0 個參數(shù):
在代碼書寫中我們會有參數(shù)不固定的情況的,在 java 中使用的是三個點來表示,而在 Python 中我用 *
來表示:
可變參數(shù)
注意:定義默認參數(shù)要牢記一點:默認參數(shù)必須指向不變對象!
在我們稍加修改后:
默認參數(shù)
函數(shù)的參數(shù)
原來返回值是一個 tuple!但是,在語法上,返回一個 tuple 可以省略括號,而多個變量可以同時接收一個 tuple,按位置賦給對應的值,所以,Python 的函數(shù)返回多值其實就是返回一個 tuple,但寫起來更方便。
但其實這只是一種假象,Python 函數(shù)返回的仍然是單一值:
在 Python 函數(shù)是可以返回多個值:
多值返回
調用函數(shù)時,如果參數(shù)個數(shù)不對,Python 解釋器會自動檢查出來,并拋出TypeError
。但是如果參數(shù)類型不對,Python 解釋器就無法幫我們檢查。但是我們可以使用 isinstance
函數(shù)來檢查:
Python 不是想 Java 是強類型語音所以我們該如何去定義一個函數(shù)類型呢?
參數(shù)檢查
缺少了pass
,代碼運行就會有語法錯誤。
如果想定義一個什么事也不做的空函數(shù),可以用pass
語句:
空函數(shù)
如果沒用使用定義 return 就默認為 None
在 Python 中,定義一個函數(shù)要使用def
語句,依次寫出函數(shù)名、括號、括號中的參數(shù)和冒號:,然后,在縮進塊中編寫函數(shù)體,函數(shù)的返回值用return
語句返回。
定義函數(shù)
還有一個要注意的就是函數(shù)指向新的變量:
重命名函數(shù)
這里我重點介紹數(shù)據(jù)類型轉換:
數(shù)據(jù)類型轉換
注意:如果傳參類型錯誤也會爆 TypeError
錯誤,并且給出錯誤信息:
注意:在調用函數(shù)時,如果傳參數(shù)量錯誤會爆 TypeError
錯誤: