如果函數(shù)沒(méi)有返回值。則函數(shù)的返回值為None。函數(shù)可以返回一個(gè)值或者對(duì)象。
def foo():
return ['xyz',1000000,-98.6]
def bar():
return 'abc',[12,'python'],'Guido' #其實(shí)返回的是一個(gè)元組。省略了圓括號(hào)('abc',[12,'python'],'Guido')
用圓括號(hào)來(lái)調(diào)用函數(shù)。如:bar() foo()
關(guān)鍵字參數(shù):允許參數(shù)缺失或者不按順序,解釋器能通過(guò)給出的關(guān)鍵字來(lái)匹配參數(shù)的值。如:
def foo(x,y):
'文檔字符串'
foo_suite
標(biāo)準(zhǔn)調(diào)用函數(shù)foo: foo(1,2) foo("bar","foo") # 按照順序輸入?yún)?shù)
關(guān)鍵字調(diào)用foo:foo(x=1,y=2)or foo(y=2,x=1) foo(y="foo",x="bar") #按照關(guān)鍵字賦值參數(shù),可以不按順序
函數(shù)示例:
#!/usr/bin/env python from operator import add, sub from random import randint, choice ops = {'+':add,'-':sub} # 全局字典 MAXTRIES = 2 # 全局嘗試次數(shù) def doprob(): #定義函數(shù)doprob op = choice("+-") #random.choice()函數(shù)隨機(jī)返回序列中的一個(gè)元素 nums = [randint(1,10) for i in range(2)] #[randint(1,10),randint(1,10)] nums.sort(reverse = True) ans = ops[op](*nums) pr = '%d %s %d =' % (nums[0],op,nums[1]) oops = 0 while True: try: if int(raw_input(pr)) == ans: print 'correct' break if oops == MAXTRIES: print 'answer\n%s%d' % (pr,ans) else: print 'incorrect...try again' oops += 1 except (KeyboardInterrupt, EOFError,ValueError): print 'invalid input ...try agin' def main(): while True: doprob() try: opt = raw_input('Again? [y]').lower() if opt and opt[0] == 'n': break except(KeyboardInterrupt,EOFError): break if __name__ == '__main__': main()
注:Python 不允許在函數(shù)未申明之前,對(duì)其進(jìn)行引用或者調(diào)用。
內(nèi)部/內(nèi)嵌函數(shù):
在函數(shù)體內(nèi)創(chuàng)建另外一個(gè)函數(shù)式完全可以的,這種函數(shù)叫做內(nèi)部/內(nèi)嵌函數(shù)。 ————內(nèi)部函數(shù)作用域只在外部函數(shù)作用域內(nèi),外部訪問(wèn)不了。
函數(shù)裝飾器 ——裝飾器就是函數(shù),裝飾器僅僅用來(lái)“裝飾”函數(shù)的包裝,返回一個(gè)修改后的函數(shù)對(duì)象,將其重新賦值原來(lái)的標(biāo)識(shí)符,并永久失去對(duì)原始函數(shù)對(duì)象的訪問(wèn)。
裝飾器的語(yǔ)法以@開頭,接著是裝飾器函數(shù)的名字和可選的參數(shù)。緊跟著裝飾器聲明的是被修飾的函數(shù)和裝飾函數(shù)的可選參數(shù)。如下:
@decorator(dec_opt_args)
def func2bdecorated(func_opt_args):
:
示例:
#!usr/bin/env python from time import ctime,sleep def tsfunc(func): def wrappedFunc(): print '[%s] %s() called' % (ctime(),func.__name__) # 時(shí)間戳調(diào)用 return func() #目標(biāo)函數(shù)調(diào)用 return wrappedFunc @tsfunc def foo(): pass foo() sleep(4) for i in range(2): sleep(1) foo()
輸出:
[Sat Jan 26 20:39:47 2013] foo() called
[Sat Jan 26 20:39:52 2013] foo() called
[Sat Jan 26 20:39:53 2013] foo() called
傳遞函數(shù)——與JS類似,python中的函數(shù) 也可以作為參數(shù)傳遞,并在函數(shù)體內(nèi)調(diào)用這些函數(shù)。
#!/usr/bin/env python # 傳遞和調(diào)用函數(shù) def convert(func,seq): 'conv.sequence of nubers to same type' return [func(eachNum) for eachNum in seq] myseq = (123,45.67,-6.2e8,9999999L) print convert(int,myseq) # 傳遞int函數(shù) print convert(long,myseq) # 傳遞long函數(shù) print convert(float,myseq) # 傳遞float函數(shù)
輸出為:
[123, 45, -620000000, 9999999]
[123L, 45L, -620000000L, 9999999L]
[123.0, 45.67, -620000000.0, 9999999.0]
函數(shù)的默認(rèn)參數(shù):python中用默認(rèn)值聲明變量的語(yǔ)法是所有的位置參數(shù)必須出現(xiàn)在任何一個(gè)默認(rèn)參數(shù)之前。
def func(posargs,defarg1=dva11,defarg2=dva2,...):
pass
抓取web頁(yè)面示例代碼:
#!/usr/bin/env python from urllib import urlretrieve def firstNonBlank(lines): for eachLine in lines: if not eachLine.strip(): continue else: return eachLine def firstLast(webpage): f = open(webpage) lines = f.readlines() f.close() print firstNonBlank(lines), # 輸出文件非空白的第一行 print '\n-----------------\n' lines.reverse() # 翻轉(zhuǎn)lines print firstNonBlank(lines), # 輸出第一行也就是倒數(shù)一行 def download(url = 'http://www.baidu.com',process = firstLast): try: retval = urlretrieve(url)[0] # 下載代碼到文件 'c:\\users\\admini~1\\appdata\\local\\temp\\tmp7msit8' except IOError: retval = None if retval: process(retval) if __name__ == '__main__': download()
返回值:
<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>百度一下,你就知道 </title><style>html,body{height:100%;}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center;}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0 auto;z-index:0;overflow:hidden;}#ftConw{width:720px;margin:0 auto;}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}#u{color:#999;padding:4px 10px 5px 0;text-align:right}#u a{margin:0 5px}#u .reg{margin:0}#m{width:720px;margin:0 auto;}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:110px;text-align:left;z-index:1;}input{border:0;padding:0}#nv{height:19px;font-size:16px;margin:0 0 4px;text-align:left;text-indent:137px;}.s_ipt_wr{width:418px;height:30px;display:inline-block;margin-right:5px;background:url(http://s1./r/www/img/i-1.0.0.png) no-repeat -304px 0;border:1px solid #b6b6b6;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.s_ipt{width:405px;height:22px;font:16px/22px arial;margin:5px 0 0 7px;background:#fff;outline:none;-webkit-appearance:none}.s_btn{width:95px;height:32px;padding-top:2px\9;font-size:14px;background:#ddd url(http://s1./r/www/img/i-1.0.0.png);cursor:pointer}.s_btn_h{background-position:-100px 0}.s_btn_wr{width:97px;height:34px;display:inline-block;background:url(http://s1./r/www/img/i-1.0.0.png) no-repeat -202px 0;*position:relative;z-index:0;vertical-align:top}#lg img{vertical-align:top;margin-bottom:3px}#lk{margin:33px 0}#lk span{font:14px "宋體"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}.tools{position:absolute;top:-4px;*top:10px;right:7px;}#mHolder{width:62px;position:relative;z-index:296;display:none}#mCon{height:18px;line-height:18px;position:absolute;cursor:pointer;padding:0 18px 0 0;background:url(http://s1./r/www/img/bg-1.0.0.gif) no-repeat right -134px;background-position:right -136px\9}#mCon span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none;filter:none\9}#mMenu,#user ul{box-shadow:1px 1px 2px #ccc;-moz-box-shadow:1px 1px 2px #ccc;-webkit-box-shadow:1px 1px 2px #ccc;filter: progid:DXImageTransform.Microsoft.Shadow(Strength=2, Direction=135, Color="#cccccc")\9;}#mMenu{width:56px;border:1px solid #9b9b9b;list-style:none;position:absolute;right:27px;top:28px;display:none;background:#fff}#mMenu a:hover{background:#ebebeb}#mMenu .ln{height:1px;background:#ebebeb;overflow:hidden;font-size:1px;line-height:1px;margin-top:-1px}#cp,#cp a{color:#666666;}#seth{display:none;behavior:url(#default#homepage)}#setf{display:none;}#sekj{margin-left:14px;}</style> ----------------- <!--708867ba7d22710c-->
可變長(zhǎng)度的參數(shù):
非關(guān)鍵字可變長(zhǎng)度參數(shù)(元組)—— 可變產(chǎn)長(zhǎng)度參數(shù)元組必須在位置和默認(rèn)參數(shù)之后,帶元組的函數(shù)普遍語(yǔ)法如下:
def function_name([formal_args,] *vargs_tuple):
"function_doc"
function_body_suite
星號(hào)操作符之后的形參將作為元組傳遞給函數(shù),元組保存了所有傳遞給函數(shù)的額外的參數(shù)(匹配了所有位置和具名參數(shù)后剩余的)。
如果沒(méi)有給出額外的參數(shù),元組為空。示例:
>>> def tupleVarARGS(arg1,arg2='defaultB',*theRest): 'display regular args and non-keyword variable args' print 'rotmal arg1:',arg1 print 'formal arg 2:',arg2 for eachXtrArg in theRest: print 'another arg:',eachXtrArg >>> tupleVarARGS('ABC') rotmal arg1: ABC formal arg 2: defaultB >>> tupleVarARGS('ABC','EFG') rotmal arg1: ABC formal arg 2: EFG >>> tupleVarARGS('ABC','EFG',123,456,78,88) rotmal arg1: ABC formal arg 2: EFG another arg: 123 another arg: 456 another arg: 78 another arg: 88 >>>
關(guān)鍵字變量參數(shù)(字典)語(yǔ)法如下:
def function_name ([formal_args,][*vargst,] **vargsd):
function_doc
functnion_body_suite
關(guān)鍵字變量參數(shù)應(yīng)該為函數(shù)定義的最后一個(gè)參數(shù),帶**,示例:
def dictVarArgs(arg1,arg2='defaultB',**theRest): 'display w regular args and keyword variable args' print 'formal arg1:',arg1 print 'formal arg2:',arg2 for eachXtrArg in theRest.keys(): print 'xtra arg %s:%s' % (eachXtrArg,str(theRest[eachXtrArg]))
輸出:
>>> dictVarArgs(1220,740.0,c='grail') formal arg1: 1220 formal arg2: 740.0 xtra arg c:grail >>> dictVarArgs(arg2='vvg',c=123,d='vvg2',arg1='asdfasd') formal arg1: asdfasd formal arg2: vvg xtra arg c:123 xtra arg d:vvg2 >>> dictVarArgs('one',d=10,e='zoo',men = ('freud','gaudi')) formal arg1: one formal arg2: defaultB xtra arg men:('freud', 'gaudi') xtra arg e:zoo xtra arg d:10
關(guān)鍵字和非關(guān)鍵字可變長(zhǎng)參數(shù)都有可能在同一函數(shù)中,只要關(guān)鍵字字典是最后一個(gè)參數(shù)并且非關(guān)鍵字元組先與它之前出現(xiàn).
def newfoo(arg1,arg2,*nkw,**kw): 'doc' print 'arg1 is:',arg1 print 'arg2 is:',arg2 for eachNKW in nkw: print 'non-keword arg:',eachNKW for eachKW in kw.keys(): print 'kew word arg "%s": %s' % (eachKW,kw[eachKW])
輸出: >>> newfoo('wolf',3,'projiects',freud=90,gamble=96) arg1 is: wolf arg2 is: 3 non-keword arg: projiects kew word arg "gamble": 96 kew word arg "freud": 90
函數(shù)式編程舉例:
#!usr/bin/env python def testit(func,*nkwargs,**kwargs): try: retval = func(*nkwargs,**kwargs) result = (True,retval) except Exception,diag: result = (False,str(diag)) return result def test(): funcs = (int,long,float) vals = (123,12.34,'1234','12.34') for eachFunc in funcs: print '_'*20 for eachVal in vals: retval = testit(eachFunc,eachVal) if retval[0]: print '%s(%s) = ' % (eachFunc.__name__,eachVal),retval[1] else: print '%s(%s) = FAILED:'% (eachFunc.__name__,eachVal),retval[1] if __name__ =='__main__': test()
輸出: ____________________ int(123) = 123 int(12.34) = 12 int(1234) = 1234 int(12.34) = FAILED: invalid literal for int() with base 10: '12.34' ____________________ long(123) = 123 long(12.34) = 12 long(1234) = 1234 long(12.34) = FAILED: invalid literal for long() with base 10: '12.34' ____________________ float(123) = 123.0 float(12.34) = 12.34 float(1234) = 1234.0 float(12.34) = 12.34
函數(shù)式編程:
匿名函數(shù)與lambda----------------------與javascript中的匿名函數(shù)類似
lambda [arg1[, arg2, ... argN]]: exprission
python 允許用lambda關(guān)鍵字創(chuàng)建匿名函數(shù)。一個(gè)完整的lambda“語(yǔ)句”代表了以個(gè)表達(dá)式,這個(gè)表達(dá)式的定義體必須和聲明放在同一行。
def add(x,y):return x + y <==> lambda x, y: x + y
def usuallyAdd2(x,y=2):return x + y <==> lambda x,y=2 : x + y
def showAllAsTuple(*z):return z <==> lambda *z : z
內(nèi)建函數(shù)apply(),filter(),map(),reduce()
----------------------------------------------------------------------------------------------
內(nèi)建函數(shù) 描述
apply(func[,nkw][,kw]) 用可選的參數(shù)來(lái)調(diào)用func,nkw為非關(guān)鍵字參數(shù),kw為關(guān)鍵字參數(shù);返回值是函數(shù)調(diào)用的返回值
filter(func,seq) 調(diào)用一個(gè)布爾函數(shù)func來(lái)遍歷迭代每一個(gè)seq中的元素;返回一個(gè)是fanc返回值為ture的元素的序列
map(func,seq1[,seq2...]) 將函數(shù)func作用于給定序列s的每個(gè)元素,并用以個(gè)列表來(lái)提供返回值;如果fanc為None,func表現(xiàn)為一個(gè)身份函 數(shù),返回一個(gè)含有每個(gè)序列中元素集合的N個(gè)原始的列表
reduce(func,seq[,init]) 將二元函數(shù)作用與seq序列的元素,每次攜帶一堆,連續(xù)地將現(xiàn)有的結(jié)果和下一個(gè)值作用在獲得的隨后的結(jié)果上,最后減少我們的序列為一個(gè)單一的返回值;如果初始值init給定,第一個(gè)比較會(huì)是init和第一個(gè)序列元素而不是序列的頭兩個(gè)元素。
apply()-------已經(jīng)被淘汰掉.....
filter() -------為已知的序列的每個(gè)元素調(diào)用給定布爾函數(shù)。每個(gè)filter返回的非零(true)值元素添加到一個(gè)列表中,返回的對(duì)象是以個(gè)從原始隊(duì)列中“過(guò)濾后”的隊(duì)列。
示例:過(guò)濾掉偶數(shù)返回奇數(shù)列表:
#!/usr/bin/env python from random import randint def odd(n): return n % 2 allNums = [] for eachNum in range(10): # 只是為了循環(huán)10次 allNums.append(randint(1,99)) # 每次添加一位隨機(jī)數(shù) print filter(odd,allNums) # 過(guò)濾
上面示例中的add()函數(shù)可以用一個(gè)lambda表達(dá)式替換:
from random import randint allNums = [] for eachNum in range(10): allNums.append(randint(1,99)) print filter(lambda n: n%2,allNums)
也可以用列表解析代替如下:
from random import randint as ri print[n for n in [ri(1,99) for i in range(9)] if n%2]
map() -- 將函數(shù)調(diào)用“映射”到每個(gè)序列的元素上,并返回含有所有返回值的列表。
map(lambda x : x+2,[0,1,2,3,4,5,6]) #[2, 3, 4, 5, 6, 7, 8] map(lambda x : x**2,range(6)) #[0, 1, 4, 9, 16, 25] [x+2 for x in range(6)] #[2, 3, 4, 5, 6, 7] [x**2 for x in range(6)] #[0, 1, 4, 9, 16, 25]
map() 使用帶多個(gè)序列的示例:
map(lambda x,y:x+y,[1,3,5],[2,4,6]) #[3, 7, 11] map(lambda x,y:(x+y,x-y),[1,3,5],[2,4,6]) #[(3, -1), (7, -1), (11, -1)] map(None,[1,3,5],[2,4,6]) #[(1, 2), (3, 4), (5, 6)] 同zip()函數(shù)
reduce() ---- 使用一個(gè)二元函數(shù)(接受兩個(gè)參數(shù),返回一個(gè)值),一個(gè)序列,一個(gè)可選的初始化器。將那個(gè)列表的內(nèi)容“減少”為以個(gè)單一的值。(它通過(guò)取出序列的頭兩個(gè)元素,將他們傳入二元行數(shù)來(lái)獲得一個(gè)單一的值來(lái)實(shí)現(xiàn)。然后又用這個(gè)值和序列的下一個(gè)元素來(lái)獲得又一個(gè)值,然后繼續(xù),知道整個(gè)序列的內(nèi)容都遍歷完畢以及最后的值會(huì)被計(jì)算出來(lái)為止).......
reduce(func,[1,2,3]) == func(func(1,3), 3) # 如果給定了初始化器,則一開始的迭代會(huì)用初始化器和易個(gè)序列的元素來(lái)進(jìn)行。
如果用程序來(lái)模擬reduce,實(shí)際就是這樣:
def mySum(x,y):return x + y allNums = range(5) #[0,1,2,3,4] total = 0 for eachNum in allNums: total = mySum(total,eachNum) print 'the total is:',total #the total is: 10
使用lambda 和 reduce(),如下:
print 'the total is:',reduce((lambda x,y:x+y),range(5))
偏函數(shù)應(yīng)用: ------ 通過(guò)functional模塊中partial()函數(shù)來(lái)創(chuàng)建PFA(偏函數(shù)).
from operator import add,mul from functools import partial add1 = partial(add,1) # add1(x) == add(1,x) mul100 = partial(mul,100) # mul100(x) == mul(100,x) print add1(10) #11 print mul100(10) #100
變量的作用域:
global語(yǔ)句:為了明確地引用一個(gè)已命名的全局變量,必須使用global語(yǔ)句,語(yǔ)法如下:
flobal var1[, var2 [, ....varN]]
def foo(): global is_this_global this_is_local = 'abc' is_this_global = 'def' print this_is_local + is_this_global foo() # abcdef
print is_this_global #def
閉包:-----與javascript中的閉包相似
簡(jiǎn)單示例:
def counter(start_at = 0): count = [start_at] def incr(): count[0] += 1 return count[0] return incr count = counter(5) print count() #6 print count() #7 print count() #8 print count() #9
變量作用域和名稱空間
#!/usr/bin/env python j,k=1,2 def proc1(): j,k = 3,4 print "j==%d and k == %d" % (j,k) k = 5 def proc2(): j = 6 proc1() #3,4 print "j==%d and k == %d" % (j,k) k = 7 proc1() # 3,4 print "j==%d and k == %d" % (j,k) #1,7 j = 8 proc2() #6,7 print "j==%d and k == %d" % (j,k) #8,7
輸出: j==3 and k == 4 j==1 and k == 7 j==3 and k == 4 j==6 and k == 7 j==8 and k == 7
遞歸:函數(shù)包含了對(duì)其自身的調(diào)用,該函數(shù)就是遞歸的。
def factorial(n): if n==0 or n==1: # 0! =1! =1 return 1 else: return (n*factorial(n-1)) >>> factorial(10) #3628800
生成器: 從語(yǔ)法上講,生成器是一個(gè)帶yield語(yǔ)句的函數(shù)。?
轉(zhuǎn)載請(qǐng)注明出處:http://www.cnblogs.com/NNUF/