目录
1.问题描述
函数多个参数如何设置
2.解决问题说明
python 多个参数可以使用元组类型的存储输入参数或者字典类型存储输入参数
参数列表,参数带*,表示可以接受输入多个参数,参数是以元组的形式存储的。
参数列表,参数带**,表示可以接受输入多个字典类型的参数,以字典的形式存储参数。
import html
def pyFuncTestTuble(*calcu):
#一个* 表示参数类型是元组,可以连续输入多个参数
try:
resCalcu=0
resOut=[]
for item in calcu:
if isinstance(item,int):
resStr = str(item)
resOut.append(resStr)
resCalcu = resCalcu + item
else:
if item.isdigit():
resCalcu = resCalcu + int(item)
resOut.append(item)
print('打印测试结果')
print(','.join(resOut))
print(str(resCalcu))
except Exception as e:
print(e)
def pyFuncTestDic(**atrs):
#两个* 表示参数类型是字典,输入多个字典类型的参数
#假设类型一致
resPrint = [' %s =\'%s\'' % item for item in atrs.items()]
print(resPrint)
def pyFuncTestTupleDic(*attrs1,**attrs2):
print(attrs1)
print(attrs2)
if __name__ == '__main__':
#测试代码
pyFuncTestTuble(1,3,3,5235,'23sd','23')
pyFuncTestDic(name='quantity',val=10)
pyFuncTestTupleDic(23,'asdg',90,name='asdg',vale=430,vat=100)
3. 注意事项
多种类型参数混合位置规则,
**参数类型排最后,*参数类型次之,单参数排最前面。
举例
def testFuncPc(p1, *p2,p3) 错误
def testFuncPc(p1, p3, *p2) 正确
def testFuncPc(*p2,**p3,p1) 错误
def testFuncPc(*p2,p1,**p3) 错误
def testFuncPc(p1,*p2,**p3) 正确