def 函数名(参数):...函数体...return 返回值
#!/usr/bin/python#coding=utf-8def test(name,age="18"):print ("my name is %s,age: %s") %(name,age)obj=test("yaobin",24)obj2=test("yaobin")[root@localhost python]# python def_test.pymy name is yaobin,age: 24my name is yaobin,age: 18
def func(name): #name :形参print namefunc(‘chenyaobin‘) #‘chenyaobin :实参‘
def func(name,age=24):print("my name is %s,age: %s") %(name,age)func("chenyaobin") #age用了默认参数func("hy","18") #指定参数结果:my name is chenyaobin,age: 24my name is hy,age: 18
def func(name,age=24):print("my name is %s,age: %s") %(name,age)func("chenyaobin") #age用了默认参数func("test",30) #按顺序的指定#func(age=30,"test") #不可以这样子,会报错func(age=30,name="test") #不按顺序的指定结果:my name is chenyaobin,age: 24my name is test,age: 30my name is test,age: 30
# 动态参数# 例子①:def func(*args):print args#执行方式一func(11,22,33,44,55,66)#执行方式二li = [11,22,33,44,55,66]func(*li)结果:(11, 22, 33, 44, 55, 66)(11, 22, 33, 44, 55, 66)
# 动态参数# 例子②:def func(**kwargs):print kwargs#执行方式一func(name="yaobin",age=18)#执行方式二li={"name":"yaobin","age":18,‘gender‘:‘male‘}func(**li)结果:{‘age‘: 18, ‘name‘: ‘yaobin‘}{‘gender‘: ‘male‘, ‘age‘: 18, ‘name‘: ‘yaobin‘}
# 动态参数# 例子③:def foo1(arg1,arg2,key1=1,key2=2,*arg,**keywords):print "arg1 parameters is ",arg1print "arg2 parameters is ",arg2print "key1 parameter is ",key1print "key2 parameter is ",key2print "Arbitrary parameter is ", argprint "keywords parameter is ",keywordsfoo1(2,3,4,5,456,789,a1=10,a2=20,a3=30)结果:arg1 parameters is 2arg2 parameters is 3key1 parameter is 4key2 parameter is 5Arbitrary parameter is (456, 789)keywords parameter is {‘a1‘: 10, ‘a3‘: 30, ‘a2‘: 20}
原文:http://www.cnblogs.com/binhy0428/p/5154261.html