#encoding=UTF-8
'''
Created on 2011-5-18
@author: lingyibin
'''
#python函数
def add(a,b):
return a+b
print 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")
#上面的结果:
'''
3
abcdef
a,b,c
a 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 #a1
printf("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 3
keyword[two] is 2
keyword[one] is 1
'''
#可以自动分辨tuple和dictionary
def 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 ",keywords
testfun(1,2,"a","b","c",one=1,two=2,three=3)
'''结果
fixed parameters is 1
optional parameter is 2
Arbitrary 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__