zoukankan      html  css  js  c++  java
  • 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'>
    
    
     
  • 相关阅读:
    浅谈大学两年
    vue的基本操作
    JS执行环境,作用域链及非块状作用域
    关于AJAX异步请求
    第一个go程序和基本语法
    Golang
    11.二叉树
    10.排序
    9.算法之顺序、二分、hash查找
    高性能异步爬虫
  • 原文地址:https://www.cnblogs.com/xieyi5420/p/10443845.html
Copyright © 2011-2022 走看看