Python函數(shù)筆記

定義函數(shù)

基礎(chǔ)語法

def my_fun(arg):
    print "run function"
    return arg * arg

如果沒有寫return語句,函數(shù)執(zhí)行之后會(huì)返回None

函數(shù)的返回值

可以有多個(gè)返回值,但是多個(gè)返回值默認(rèn)是以元組的方式返回,相當(dāng)于返回了一個(gè)元組

>>> def my_fun3(arg1, arg2):
...     x = arg1 + 59
...     y = arg2 + 59
...     return x,y
... 
>>> r = my_fun3(12,78)
>>> type(r)
<type 'tuple'>
>>> print r
(71, 137)
>>> r, t = my_fun3(56, 89)
>>> print r,t
115 148

空函數(shù)

def my_fun2():
    pass

調(diào)用函數(shù)

function_name()是調(diào)用函數(shù)的基本語法

  • function_name 是函數(shù)的名字(可以使自定義函數(shù),可以使內(nèi)置函數(shù),可以使第三方模塊中的函數(shù))
  • () 括號(hào)里放的是該函數(shù)的參數(shù),如果沒有參數(shù),可以為空
>>> def my_fun4():
...     print "hello"
...     print "world"
... 
>>> my_fun4()
hello
world
# my_fun4函數(shù)里面只有兩行打印語句,沒有定義返回值,所以返回值默認(rèn)為空(None)
>>> s = my_fun4()
hello
world
>>> print s
None
>>> type(s)
<type 'NoneType'>
>>> 
>>> 
>>> def my_fun5():
...     return "hello world"
... 
# my_fun5函數(shù)里面定義了返回值
>>> ss = my_fun5()
>>> print ss
hello world
>>> type(ss)
<type 'str'>

函數(shù)的參數(shù)

默認(rèn)參數(shù)

拿一個(gè)簡單的冪運(yùn)算舉例
n=2即為默認(rèn)參數(shù),在調(diào)用該函數(shù)時(shí),如果只指定了一個(gè)參數(shù),那變量n將默認(rèn)等于2

>>> def my_fun6(x, n=2):
...     return x ** n
... 
>>> my_fun6(3)
9
>>> my_fun6(3,3)
27

也可以將兩個(gè)參數(shù)都設(shè)置有默認(rèn)變量,這樣該函數(shù)即使不傳參,也能正常工作

>>> my_fun6()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_fun6() takes at least 1 argument (0 given)
>>> def my_fun7(x=3,n=2):
...     return x ** n
... 
>>> my_fun7()
9

使用默認(rèn)參數(shù)的注意事項(xiàng)

  • 必選參數(shù)在前,默認(rèn)參數(shù)在后,否則Python解釋器會(huì)報(bào)錯(cuò)

  • 當(dāng)函數(shù)需要多個(gè)參數(shù)的時(shí)候,將變化較大的參數(shù)放在前面,變化小的放在后面作為默認(rèn)參數(shù)

  • 默認(rèn)參數(shù)必須指向不可變對(duì)象(eg: int, string, float)

可變參數(shù)

可以折衷地使用列表或元組實(shí)現(xiàn)可變長參數(shù)
(以下交互終端使用了ipython)

In [1]: def cal(numbers):
   ...:     sum = 0
   ...:     for i in numbers:
   ...:         sum = sum + i
   ...:     return sum

In [2]: cal([1,2,3])
Out[2]: 6

In [3]: cal((1,2,3))
Out[3]: 6

可變參數(shù)的關(guān)鍵字為*星號(hào)。在設(shè)置函數(shù)的接收參數(shù)時(shí),前面加上一個(gè)星號(hào),則函數(shù)內(nèi)部接收到的所有參數(shù)會(huì)自動(dòng)轉(zhuǎn)化為一個(gè)元組

In [5]: def cal(*numbers):
   ...:     sum = 0
   ...:     for i in numbers:
   ...:         sum = sum + i
   ...:     return sum
   ...: 

In [6]: cal(1,2,3)
Out[6]: 6

In [7]: cal()
Out[7]: 0

In [8]: cal(1,2,3,4,5,6)
Out[8]: 21
In [9]: def cal(*numbers):
   ...:     return type(numbers)
   ...: 

In [10]: cal()
Out[10]: tuple

關(guān)鍵字參數(shù)

可變長參數(shù)傳入到函數(shù)內(nèi)部會(huì)自動(dòng)轉(zhuǎn)換成一個(gè)元組;而關(guān)鍵字參數(shù)傳入到函數(shù)內(nèi)部會(huì)自動(dòng)轉(zhuǎn)換成一個(gè)字典
關(guān)鍵字參數(shù)的關(guān)鍵字是**兩個(gè)星號(hào)

In [12]: def person(name, age, **otherkeyword):
   ....:     print 'name: ', name, '\n', 'age: ', age, '\n', 'otherInfo: ', otherkeyword
   ....:    
 
In [13]: person('ps',24)
name:  ps
age:  24
otherInfo:  {}
 
In [14]: person('ps',24,city='BJ')
name:  ps
age:  24
otherInfo:  {'city': 'BJ'}
 
In [15]: person('ps',24,city='BJ',job='Engineer')
name:  ps
age:  24
otherInfo:  {'city': 'BJ', 'job': 'Engineer'}
 
In [16]: dict_kw = {'city': 'BJ', 'job': 'Engineer'}
 
In [17]: dict_kw
Out[17]: {'city': 'BJ', 'job': 'Engineer'}
 
In [18]: person('ps',24,**dict_kw)
name:  ps
age:  24
otherInfo:  {'city': 'BJ', 'job': 'Engineer'}

參數(shù)組合

上面提到了四種參數(shù)(必選參數(shù)、默認(rèn)參數(shù)、可變參數(shù)、關(guān)鍵字參數(shù)),這四種參數(shù)可以一起使用。
參數(shù)定義的順序必須是:必須參數(shù)、默認(rèn)參數(shù)、可變參數(shù)、關(guān)鍵字參數(shù)

In [21]: def func(a, b, c=0, *args, **kw):
   ....:     print 'a:', a, '\n', 'b:', b, '\n', 'c:', c, '\n', 'tuple_args:', args, '\n', 'dict_kw:', kw
   ....:     

In [22]: func(1,2)
a: 1 
b: 2 
c: 0 
tuple_args: () 
dict_kw: {}

In [23]: func(1,2,c=3)
a: 1 
b: 2 
c: 3 
tuple_args: () 
dict_kw: {}

In [24]: func(1,2,c=3,4,5)
  File "<ipython-input-24-9272b7482bc9>", line 1
SyntaxError: non-keyword arg after keyword arg

In [25]: func(1,2,3,4,5)
a: 1 
b: 2 
c: 3 
tuple_args: (4, 5) 
dict_kw: {}

In [26]: func(1,2,3,4,5,x=59)
a: 1 
b: 2 
c: 3 
tuple_args: (4, 5) 
dict_kw: {'x': 59}

注意

  • *args是可變參數(shù),接收一個(gè)tuple

  • **kw是關(guān)鍵字參數(shù),接收一個(gè)dict

  • 在必選參數(shù),默認(rèn)參數(shù),可變長參數(shù)和關(guān)鍵字參數(shù)混合使用時(shí),默認(rèn)參數(shù)在復(fù)制時(shí)不要指定參數(shù)名,如上例的c=3 否則會(huì)報(bào)錯(cuò)

常用內(nèi)置函數(shù)

isinstance

isinstance函數(shù)判斷對(duì)象類型

>>> class obj1:
...     pass
... 
>>> o = obj1()
>>> t = (1,2,3)
>>> l = [1,2,3]
>>> d = {'a':1,'b':2,'c':3}
>>> s = 'string'
>>> i = 6
>>> f = 5.9
>>> 
>>> print isinstance(o, obj1)
True
>>> print isinstance(t, tuple)
True
>>> print isinstance(l, list)
True
>>> print isinstance(d, dict)
True
>>> print isinstance(s, str)
True
>>> print isinstance(i, int)
True
>>> print isinstance(f, float)
True
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容