程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python函数参数

发布于2019-08-07 18:28     阅读(880)     评论(0)     点赞(5)     收藏(0)


一个参数:
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.pythonheidong.com/blog/article/12091/4c1a711e463ff67b367a/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

5 0
收藏该文
已收藏

评论内容:(最多支持255个字符)