python学习笔记二(函数)
#encoding=UTF-8'''Created on 2011-5-18@author: lingyibin'''#python函数def add(a,b): return a+bprint add(1,2)print add("abc","def")#默认参数def myjoin(str,sep=","): return sep.join(str)print myjoin(["a","b","c"])print myjoin(["a","b","c"],"\t")#上面的结果:'''3abcdefa,b,ca b c'''#但注意一点,如果一个参数是可以选的话,它后面的参数也必须是可以选的。如下:'''def myrange(start = 0,stop,step=1): print stop,start,step;#报错:SyntaxError: non-default argument follows default argument'''#tuple,可选参数个数def printf(format,*arg): print type(arg) #SyntaxError: non-default argument follows default argument print format%arg #a1printf("a%d",1) #dectionary,可选参数个数def printf2(format,**keyword): for k in keyword.keys(): print "keyword[%s] is %s"%(k,keyword[k])printf2("ok",one=1,two=2,three=3)'''结果:keyword[three] is 3keyword[two] is 2keyword[one] is 1'''#可以自动分辨tuple和dictionarydef testfun(fixed,optional=1,*arg,**keywords): print "" print "fixed parameters is ",fixed print "optional parameter is ",optional print "Arbitrary parameter is ", arg print "keywords parameter is ",keywordstestfun(1,2,"a","b","c",one=1,two=2,three=3)'''结果fixed parameters is 1optional parameter is 2Arbitrary parameter is ('a', 'b', 'c')keywords parameter is {'three': 3, 'two': 2, 'one': 1}''''''每一个函数都是一个对象。都有一个__doc__属性,它在函数的开头处定义,如要没定义,则默认为空'''def myfun(): """hello,this is lingyibin """ return print myfun.__doc__'''结果:hello,this is lingyibin '''print " ".join.__doc__print range.__doc__?