python函数参数

一个参数:
def show(a):
    print(a)
show(1)
执行结果:
1

两个参数:
def show(a1,a2):
    print(a1,a2)
show(1,2)
执行结果:
1 2

默认参数:
def show(a1,a2=3):#默认参数a2=3
    print(a1,a2)
show(1,)     #执行函数时,不加入实际参数将执行默认参数
执行结果:
1 3
def show(a1,a2=3):
    print(a1,a2)
show(1,2)  #执行函数的时候加入实际参数,默认参数将不执行
执行结果:
1 2

指定参数:
def show(a1,a2):
    print(a1,a2)
show(a2=222,a1=111)#执行函数时,指定参数的值
执行结果:
111 222

动态参数:
def show(*a1):     #*默认会把传入参数改为元祖
    print(a1,type(a1))
show(1,2,3,4,5,6,7)
执行结果:
(1, 2, 3, 4, 5, 6, 7) <class 'tuple'>

def show(**a1):   #**默认把传入参数改为字典
    print(a1,type(a1))
show(k1=1,k2=2,k3=3)
执行结果:
{'k1': 1, 'k2': 2, 'k3': 3} <class 'dict'>

def show(*a1,**a2):    #一个*必须在前,**必须在后
    print(a1,type(a1))
    print(a2,type(a2))
show(1,2,3,4,5,k1=1,k2=2)#传参数时也要遵守元祖元素在前,字典元素在后的原则
执行结果:
(1, 2, 3, 4, 5) <class 'tuple'>
{'k1': 1, 'k2': 2} <class 'dict'>

def show(*a1,**a2):
    print(a1,type(a1))
    print(a2,type(a2))
lis = [1,2,3,4,5]
dic = {'k1':'v1','k2':'v2'}
show(lis,dic)        #默认都会把lis和dic当元素加到*a1中去
执行结果:
([1, 2, 3, 4, 5], {'k1': 'v1', 'k2': 'v2'}) <class 'tuple'>
{} <class 'dict'> 

show(*lis,**dic) #要将lis和dic对应到a1和a2中,需要在前面对应添加*lis和**dic
执行结果:
(1, 2, 3, 4, 5) <class 'tuple'>
{'k1': 'v1', 'k2': 'v2'} <class 'dict'>

 
原文地址:https://www.cnblogs.com/xieyi5420/p/10443845.html