定義函數(shù)
基礎(chǔ)語法
def my_fun(arg):
print "run function"
return arg * arg
如果沒有寫return
語句,函數(shù)執(zhí)行之后會返回None
函數(shù)的返回值
可以有多個返回值,但是多個返回值默認(rèn)是以元組的方式返回,相當(dāng)于返回了一個元組
>>> 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ù))
- () 括號里放的是該函數(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ù)
拿一個簡單的冪運算舉例
n=2
即為默認(rèn)參數(shù),在調(diào)用該函數(shù)時,如果只指定了一個參數(shù),那變量n
將默認(rèn)等于2
>>> def my_fun6(x, n=2):
... return x ** n
...
>>> my_fun6(3)
9
>>> my_fun6(3,3)
27
也可以將兩個參數(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ù)的注意事項
必選參數(shù)在前,默認(rèn)參數(shù)在后,否則Python解釋器會報錯
當(dāng)函數(shù)需要多個參數(shù)的時候,將變化較大的參數(shù)放在前面,變化小的放在后面作為默認(rèn)參數(shù)
默認(rèn)參數(shù)必須指向不可變對象(eg: int, string, float)
可變參數(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)鍵字為*
星號。在設(shè)置函數(shù)的接收參數(shù)時,前面加上一個星號,則函數(shù)內(nèi)部接收到的所有參數(shù)會自動轉(zhuǎn)化為一個元組
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)部會自動轉(zhuǎn)換成一個元組
;而關(guān)鍵字參數(shù)傳入到函數(shù)內(nèi)部會自動轉(zhuǎn)換成一個字典
關(guān)鍵字參數(shù)的關(guān)鍵字是**
兩個星號
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ù),接收一個tuple
**kw是關(guān)鍵字參數(shù),接收一個dict
在必選參數(shù),默認(rèn)參數(shù),可變長參數(shù)和關(guān)鍵字參數(shù)混合使用時,默認(rèn)參數(shù)在復(fù)制時不要指定參數(shù)名,如上例的
c=3
否則會報錯
常用內(nèi)置函數(shù)
isinstance
isinstance函數(shù)判斷對象類型
>>> 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