Python中函数的参数传递与可变长参数 Python中函数的参数传递与可变长参数

转自旭东的博客原文 Python中函数的参数传递与可变长参数

Python中传递参数有以下几种类型:

(1)像C++一样的默认缺省函数

(2)根据参数名传参数

(3)可变长度参数

示例如下:

(1)默认参数

1 def foo(text,num=0):
2     print text,num 3 4 foo("asd") #asd 0 5 foo("def",100) #def 100

(2)参数名传递方式

1 def foo(ip,port):
2     print "%s:%d" % (ip,port) 3 4 foo("192.168.1.0",3306) #192.168.1.0:3306 5 foo(port=8080,ip="127.0.0.1") #127.0.0.1:8080

(3)可变长度参数

 
#coding:utf-8       #设置python文件的编码为utf-8,这样就可以写入中文注释
def foo(arg1,*tupleArg,**dictArg):
    print "arg1=",arg1  #formal_args
    print "tupleArg=",tupleArg  #()
    print "dictArg=",dictArg    #[]
foo("formal_args")

上面函数中的参数,tupleArg前面“*”表示这个参数是一个元组参数,从程序的输出可以看出,默认值为();dicrtArg前面有“**”表示这个字典参数(键值对参数)。可以把tupleArg、dictArg看成两个默认参数。多余的非关键字参数,函数调用时被放在元组参数tupleArg中;多余的关键字参数,函数调用时被放字典参数dictArg中。

 下面是可变长参数的一些用法:

#coding:utf-8       #设置python文件的编码为utf-8,这样就可以写入中文注释
def foo(arg1,arg2="OK",*tupleArg,**dictArg):
    print "arg1=",arg1
    print "arg2=",arg2
    for i,element in enumerate(tupleArg):
        print "tupleArg %d-->%s" % (i,str(element))
    for  key in dictArg:
        print "dictArg %s-->%s" %(key,dictArg[key])

myList=["my1","my2"]
myDict={"name":"Tom","age":22}
foo("formal_args",arg2="argSecond",a=1)
print "*"*40
foo(123,myList,myDict)
print "*"*40
foo(123,rt=123,*myList,**myDict)

猜你喜欢

转载自www.cnblogs.com/arxive/p/9900570.html